Initialize a crate

I am trying to port a C library to Rust, which requires initialization/finalization, e.g.

// some code

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?

You should probably not make the context static, much less a singleton. Instead, use once_cell::Lazy to perform initialization.

Good to know the once_cell, but now I am wondering why static_init would not work, e.g.

static _LIBXXX_CONTEXT: LibXXXContext = LibXXXContext::new();

would not trigger the initialize process.

Rust doesn't run any code before main as a matter of principle.

1 Like

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.