napi-rs/examples/napi-compat-mode/src/cleanup_env.rs
forehalo 2467b7139b
Introduce #[napi] procedural macro to automation development boilerplate (#696)
* napi procedural macro for basic rust/JavaScript types
* introduce the `compat-mode` for `napi` and `napi-derive` crates for backward compatible
* remove #[inline] and let compiler to decide the inline behavior
* cli now can produce the `.d.ts` file for native binding
* many tests and example for the new procedural macro

Co-authored-by: LongYinan <lynweklm@gmail.com>
2021-09-23 01:29:09 +08:00

27 lines
855 B
Rust

use napi::{
CallContext, CleanupEnvHook, ContextlessResult, Env, JsExternal, JsObject, JsUndefined, Result,
};
#[contextless_function]
fn add_cleanup_hook(mut env: Env) -> ContextlessResult<JsExternal> {
let hook = env.add_env_cleanup_hook((), |_| {
println!("cleanup hook executed");
})?;
env.create_external(hook, None).map(Some)
}
#[js_function(1)]
fn remove_cleanup_hook(ctx: CallContext) -> Result<JsUndefined> {
let hook_external = ctx.get::<JsExternal>(0)?;
let hook = *ctx
.env
.get_value_external::<CleanupEnvHook<()>>(&hook_external)?;
ctx.env.remove_env_cleanup_hook(hook)?;
ctx.env.get_undefined()
}
pub fn register_js(exports: &mut JsObject) -> Result<()> {
exports.create_named_method("addCleanupHook", add_cleanup_hook)?;
exports.create_named_method("removeCleanupHook", remove_cleanup_hook)?;
Ok(())
}