我一直在用Rust编写一个使用一些OpenGL的应用程序,我观察到了在rust代码中访问/管理OpenGl的趋势。通常情况下,管理或创建OpenGl上下文似乎需要unsafe。
为什么这些示例需要不安全的代码?我没有遇到任何问题,因为这个不安全的指示器,但我只是好奇为什么它在那里。这些不安全的需求会给开发人员带来什么样的问题或约束呢?
来自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));
}
//... //...
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();
});
}
//...发布于 2021-04-18 03:23:14
OpenGL被实现为一个带有C ABI的库。如果你想从rust中调用一个C函数,它总是意味着你的have to use unsafe,因为C实现对rust的安全特性一无所知,自然也不支持它们。此外,OpenGL在其应用程序接口中使用原始指针从GL传递数据或向GL传递数据,这也需要rust中的unsafe代码。
https://stackoverflow.com/questions/67141789
复制相似问题