Reputation: 3401
I've been writing an app in Rust that uses some OpenGL, and I've observed a trend in how OpenGl is accessed/managed in rust code. Frequently it seems that managing or creating an OpenGl context requires unsafe
.
Why do these examples require unsafe code? I haven't been running into any problems because of this unsafe designator, but I'm just curious as to why its there. What kind of problems or constraints do these unsafe requirements impose on developers?
from glutins Multi-Window example
//...
let mut windows = std::collections::HashMap::new();
for index in 0..3 {
let title = format!("Charming Window #{}", index + 1);
let wb = WindowBuilder::new().with_title(title);
let windowed_context = ContextBuilder::new().build_windowed(wb, &el).unwrap();
//uses unsafe code
let windowed_context = unsafe { windowed_context.make_current().unwrap() };
let gl = support::load(&windowed_context.context());
let window_id = windowed_context.window().id();
let context_id = ct.insert(ContextCurrentWrapper::PossiblyCurrent(
ContextWrapper::Windowed(windowed_context),
));
windows.insert(window_id, (context_id, gl, index));
}
//...
from fltk-rs glow demo
//...
unsafe {
let gl = glow::Context::from_loader_function(|s| {
win.get_proc_address(s) as *const _
});
let vertex_array = gl
.create_vertex_array()
.expect("Cannot create vertex array");
gl.bind_vertex_array(Some(vertex_array));
let program = gl.create_program().expect("Cannot create program");
//...
win.draw(move |w| {
gl.clear(glow::COLOR_BUFFER_BIT);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
w.swap_buffers();
});
}
//...
Upvotes: 3
Views: 892
Reputation: 45322
OpenGL is implemented as a library with a C ABI. If you want to call a C function from rust, it always means you have to use unsafe
because the C implementation knows nothing about the safety features of rust and naturally doesn't support them. Furthermore, OpenGL uses raw pointers in its API to pass data from or to the GL, which also requires unsafe
code in rust.
Upvotes: 3