Store a *mut libc::c_void type entire the program


A return value of a c++ foreign function has *mut libc::c_void type (equal to void* in c++). how can I store and save this value entire my program, initialize it first, and use it whenever I want, like a static variable?

I can't store a *mut libc::c_void type directly like this:

static CHILD: *mut libc::c_void = createChild();

I get this error:

*mut c_void cannot be shared between threads safely the trait Sync is not implemented for *mut c_void shared static variables must have a type that implements Sync.

I'm familiar with lazy_static, and it' not possible too.

also, I need to free this pointer in C++ when I'm done with using it. so, I kinda need a specific drop function too. I know that 'static' does not have drop. but if you have an idea, I would be happy to hear it.

This question probably belongs on, but I happen to have an answer off the top of my head: Cast the value to libc::uintptr_t before storing it. I had to do this in one of my programs to work around the fact that some C libraries define pthread_t to be a C typedef for void *, and others define it as an opaque integer. The libc crate follows suit, which means that whether libc::pthread_t is Send varies based on the underlying OS. (It ought to be Send always.)

thanks, it worked with casting to libc::uintptr_t, now have another question,

how can I have a function which is called at the end of my program? (in this case I have to free the *mut libc::c_void type pointer in C++)

One approach is to use something like drop_guard. If you construct a guard at the start of main, it will run your custom drop logic when either unwinding or returning from main.

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