xis19
1
I am trying to port a C library to Rust, which requires initialization/finalization, e.g.
libxxx_initialize();
// some code
libxxx_cleanup();
I would like this automated, and my first approach is
struct LibXXXContext;
impl LibXXXContext {
pub fn new() -> Self {
unsafe { libxxx_initialize(); }
}
}
impl Drop for LibXXXContext {
fn drop(&mut self) {
unsafe { libxxx_cleanup(); }
}
}
yet it is not working as
static _LIBXXX_CONTEXT: LibXXXContext = LibXXXContext::new();
will fail since new
is not const and can not be const. Is there any other way to achieve this?
H2CO3
2
You should probably not make the context static
, much less a singleton. Instead, use once_cell::Lazy
to perform initialization.
xis19
3
Good to know the once_cell
, but now I am wondering why static_init would not work, e.g.
#[dynamic]
static _LIBXXX_CONTEXT: LibXXXContext = LibXXXContext::new();
would not trigger the initialize process.
kornel
4
Rust doesn't run any code before main
as a matter of principle.
1 Like
system
Closed
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.