pub struct Function<F: NapiValueT>(/* private fields */);
Implementations§
Source§impl<F: NapiValueT> Function<F>
impl<F: NapiValueT> Function<F>
Sourcepub fn new<T, R>(
env: NapiEnv,
name: Option<impl AsRef<str>>,
func: impl FnMut(JsObject, T) -> NapiResult<R>,
) -> NapiResult<Function<R>>where
T: FromJsArgs,
R: NapiValueT,
pub fn new<T, R>(
env: NapiEnv,
name: Option<impl AsRef<str>>,
func: impl FnMut(JsObject, T) -> NapiResult<R>,
) -> NapiResult<Function<R>>where
T: FromJsArgs,
R: NapiValueT,
This API allows an add-on author to create a function object in native code. This is the primary mechanism to allow calling into the add-on’s native code from JavaScript. The newly created function is not automatically visible from script after this call. Instead, a property must be explicitly set on any object that is visible to JavaScript, in order for the function to be accessible from script. In order to expose a function as part of the add-on’s module exports, set the newly created function on the exports object. A sample module might look as follows:
napi_value SayHello(napi_env env, napi_callback_info info) {
printf("Hello\n");
return NULL;
}
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);
if (status != napi_ok) return NULL;
status = napi_set_named_property(env, exports, "sayHello", fn);
if (status != napi_ok) return NULL;
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
Given the above code, the add-on can be used from JavaScript as follows:
const myaddon = require('./addon');
myaddon.sayHello();
The string passed to require() is the name of the target in binding.gyp responsible for creating the .node file.
Any non-NULL data which is passed to this API via the data parameter can be associated with the resulting JavaScript function (which is returned in the result parameter) and freed whenever the function is garbage-collected by passing both the JavaScript function and the data to napi_add_finalizer.
JavaScript Functions are described in Section 19.2 of the ECMAScript Language Specification.
Sourcepub fn call<T>(&self, this: JsObject, args: T) -> NapiResult<F>where
T: ToJsArgs,
pub fn call<T>(&self, this: JsObject, args: T) -> NapiResult<F>where
T: ToJsArgs,
This method allows a JavaScript function object to be called from a native add-on. This is the primary mechanism of calling back from the add-on’s native code into JavaScript. For the special case of calling into JavaScript after an async operation, see napi_make_callback.
Sourcepub fn new_instance<T, Args>(&self, args: Args) -> NapiResult<JsObject>
pub fn new_instance<T, Args>(&self, args: Args) -> NapiResult<JsObject>
This method is used to instantiate a new JavaScript value using a given napi_value that represents the constructor for the object.