Reputation: 10895
I am currently porting an OpenGL application written in C++ to Rust and came across a design question that may have other implications since I am pretty new to Rust.
As of now I am using a combination of glutin
and gl_generator
. Generating global functions in the bindings module yields the following API:
gl::load_with(|symbol| context.get_proc_address(symbol));
// anywhere else since it's global
gl::CreateProgram();
This is pretty much the same paradigm that I used for my wrapper classes in C++ that access global methods:
// ...
FShader::~FShader() {
if (Handle != 0) {
glDeleteProgram(Handle);
}
}
auto FShader::bind() const -> void { glUseProgram(Handle); }
// ...
After reading further posts on the internet I noticed some people suggesting to use the struct generator and work with an objects rather than global methods.
let gl = Rc::new(gl::Gl::load_with(|symbol| context.get_proc_address(symbol)));
// ...
pub struct Shader {
gl: Rc<gl::Gl>,
handle: u32,
}
impl Drop for Shader {
fn drop(&mut self) {
unsafe {
self.gl.DeleteProgram(self.handle);
}
}
}
impl Shader {
pub fn new(gl: Rc<gl::Gl>) -> Result<Shader, ()> {
let handle = unsafe { gl.CreateProgram() };
// ...
Ok(Shader { gl, handle })
}
}
This approach is definitely more verbose since all wrapper classes would have to store a ref to the gl::Gl
object to be able to release resources for instance. The signature of Drop::drop
seems to be the reason why sharing the reference across objects is necessary. Are there any other advantages for doing this? Is the use of a Rc
the best approach or is it more reasonable to work with regular references?
Upvotes: 1
Views: 347
Reputation: 48
Using regular references would probably be better performance-wise, as Rc
s has the overhead from reference counting.
However, if you were to use references, you would have to deal lots of lifetime annotations, which could make the code more verbose. Additionally, you would also have to keep the gl::GL
object alive for as long as you are using OpenGL (which I presume is the entire lifetime of the program).
Upvotes: 0