Global mutable static? Initialized at runtime

I'm writing a plugin for another C program, the API that I must adhere to forces me to keep a static state variable.

Basically what I have to implement is like this:

pub extern "C" fn initialize(data: *const some_c_struct);

pub extern "C" fn get_c() -> c_int;

pub extern "C" fn get_b() -> c_uint;

pub extern "C" fn get_c() -> c_char;

In order to allow all the get_x functions to function properly, there are two things that I have to save in static variables:

  1. the pointer to the struct that I get in initialize
  2. Some data that's generated in initialize

This is an oversimplification of the code, but the truths remain: the only way to generate the data is in initialize, using the information provided in the struct.

All the other functions except initalize are only going to access the two static variables for reads.

initialize may be called multiple times, overriding the static variables and freeing whatever was there.

It is guaranteed that no other functions are going to be called at the same time.

I've been trying to find a way to do that with maximal simplicity and minimal use of unsafe code, but haven't been able to figure it out.

Initialize is probably going to contain some unsafe, but the other functions should be safe.

lazy_static doesn't help much since I can't intialize the data before initialize is called.

Any advice or help would be appreciated.

Would once_cell::OnceCell work? You could also use a thread_local. Initializing the tread_local with some null value to start with.


Does this work:

lazy_static holds a Mutex<Option<_>>. This lets you re-initialize it at each initialize().

Ah, thread_local would probably be better (assuming the plugin is only called on a single thread).

Thanks, I'll try thread_local, though I'm not really fond of how its operated.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.