I'm in the processing of rewriting an existing C application that uses SDL2 in rust.
As part of that process, I'm incrementally converting the existing program and have been doing that by building a rust static library that the C program links against with all of the functions exported using the C ABI which has been working great.
I've reached the point now where I need access to the SDL context:
However, I've hit an unexpected blocker. The main program loop isn't ready to be converted to rust yet, and the sdl2 rust bindings return a special Rc<>-based object as SDL requires that SDL functions are only called from the main thread.
Because the rust library must be the one to create the Sdl context so that I can call various methods related to it, I would like it to be a global static in the library so I can continue to incrementally rewrite the rest of the C program after the C program calls a library function to init SDL.
I found lazy_static, which seemed promising, but I haven't figured out the incantation required to use it. What I have so far is something like this:
extern crate sdl2;
#[macro_use]
extern crate lazy_static;
lazy_static! {
pub static ref sdl_context: &'static sdl2::Sdl = {
sdl2::init().unwrap()
};
}
This fails to compile, unsurprisingly, with something like:
error[E0277]: `Rc<SdlDrop>` cannot be shared between threads safely
--> chroma\src\lib.rs:337:1
|
337 | / lazy_static! {
338 | | pub static ref sdl_context: &'static sdl2::Sdl = {
339 | | sdl2::init().unwrap()
340 | | };
341 | | }
| |_^ `Rc<SdlDrop>` cannot be shared between threads safely
I'm well aware that Rc<> things cannot be shared between threads safely. However, I won't be using this from anywhere but the main thread -- this is, in practice, a single-threaded program.
I haven't found any examples and I'm hoping someone else has had to do something like this before or can explain what minimal change I can make to make the compiler happy.
Using thread_local here didn't seem like the right solution here unless that's just the way of making the compiler shut up and it's fine since I'll only ever really be using one thread anyway.
I'm guessing I need to use RefCell instead of lazy_static? Ideas?