Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(napi): make napi_register_module_v1 pub #1747

Merged
merged 3 commits into from Oct 9, 2023

Conversation

MarkusJx
Copy link
Contributor

@MarkusJx MarkusJx commented Oct 8, 2023

I'd like to use classes created by napi-rs inside a Node.js instance which is created using rust-nodejs. For this to work, the classes need to be exported to the node runtime using napi::bindgen_prelude::napi_register_module_v1, which is currently not accessible from outside its module.

This PR makes this method accessible from outside its module.

Code I'm using to initialize napi-rs modules inside a node vm created by rust-nodejs

If someone is interested in how I'm using the napi_register_module_v1 method:

use napi::bindgen_prelude::napi_register_module_v1;
use napi::sys::{napi_env, napi_value};
use napi::Env;
use nodejs::run_raw;
use std::ffi::c_void;
use std::ptr::null_mut;

static ONCE: Once = Once::new();

unsafe fn run_napi<F: for<'a> FnOnce(Env)>(f: F) -> i32 {
    static mut MODULE_INIT_FN: *mut c_void = null_mut();

    let mut module_init_fn = Some(f);
    MODULE_INIT_FN = (&mut module_init_fn) as *mut Option<F> as _;

    unsafe extern "C" fn napi_reg_func<F: for<'a> FnOnce(Env)>(
        env: napi_env,
        exports: napi_value,
    ) -> napi_value {
        ONCE.call_once(|| {
            napi_register_module_v1(env, exports);
        });

        let module_init_fn = (MODULE_INIT_FN as *mut Option<F>).as_mut().unwrap();
        let module_init_fn = module_init_fn.take().unwrap();
        MODULE_INIT_FN = null_mut();
        module_init_fn(Env::from_raw(env));

        exports
    }

    run_raw(napi_reg_func::<F> as _)
}

@Brooooooklyn Brooooooklyn changed the title feat(napi): make napi_register_module_v1 pub chore(napi): make napi_register_module_v1 pub Oct 9, 2023
@Brooooooklyn Brooooooklyn merged commit 9b4beb8 into napi-rs:main Oct 9, 2023
46 of 49 checks passed
@MarkusJx MarkusJx deleted the feat/pub-napi-register branch October 9, 2023 11:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants