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

Can references be shared between different modules/envs? #448

Closed
cutsoy opened this issue Feb 21, 2023 · 3 comments
Closed

Can references be shared between different modules/envs? #448

cutsoy opened this issue Feb 21, 2023 · 3 comments

Comments

@cutsoy
Copy link

cutsoy commented Feb 21, 2023

Not sure if this is the right repo to ask this, but I was wondering if references to objects (i.e. created with napi_create_reference) can be shared between different native modules and/or napi_envs (assuming of course it runs in the same instance of Node).

For example:

  1. a native module foo that receives an object from JS and creates a reference to keep it around a bit longer;
  2. native module foo makes a native C call to native module bar and passes the reference to bar;
  3. JS calls native module bar and bar calls napi_get_reference_value (with a different napi_env).
@mhdawson
Copy link
Member

mhdawson commented Mar 2, 2023

In general I don't think it's safe to use something created with one env, in another env.

@gabrielschulhof
Copy link
Collaborator

gabrielschulhof commented Apr 8, 2023

@cutsoy I agree with @mhdawson. It would be safer for modules foo and bar to coordinate via JS. For example, module bar can expose a function that receives as its sole parameter the desired object. Then, the function can be passed into module foo , which will call it with the object. Module bar can then create a second reference to the same object. So, roughly,

foo.sendObject(bar.receiveObject);

where sendObject is implemented as

static napi_value SendObject(napi_env env, napi_callback_info info) {
  napi_value cb, the_object;
  size_t argc = 1;
  napi_get_cb_info(env, info, &argc, &cb, NULL, NULL);
  napi_get_reference_value(env, the_object_ref, &the_object);
  napi_call_function(env, the_object, cb, 1, &the_object, NULL);
}

@gabrielschulhof
Copy link
Collaborator

@cutsoy I hope this answers your question. If you have any further questions, please feel free to re-open this issue or open a new one.

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

No branches or pull requests

3 participants