nodejs / abi-stable-node

Repository used by the Node-API team to manage work related to Node-API and node-addon-api
239 stars 47 forks source link

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

Closed cutsoy closed 1 year ago

cutsoy commented 1 year ago

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 commented 1 year ago

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

gabrielschulhof commented 1 year ago

@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 commented 1 year ago

@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.