2020-06-21 19:10:06 +08:00
|
|
|
use std::convert::TryInto;
|
|
|
|
|
2020-11-25 17:42:14 +08:00
|
|
|
use napi::{CallContext, JsExternal, JsNumber, JsObject, Result};
|
2020-06-21 19:10:06 +08:00
|
|
|
|
|
|
|
struct NativeObject {
|
|
|
|
count: i32,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[js_function(1)]
|
|
|
|
pub fn create_external(ctx: CallContext) -> Result<JsExternal> {
|
|
|
|
let count = ctx.get::<JsNumber>(0)?.try_into()?;
|
|
|
|
let native = NativeObject { count };
|
2020-12-22 11:57:26 +08:00
|
|
|
ctx.env.create_external(native, None)
|
2020-06-21 19:10:06 +08:00
|
|
|
}
|
|
|
|
|
2021-03-11 19:02:42 +08:00
|
|
|
#[js_function(1)]
|
|
|
|
pub fn create_external_with_hint(ctx: CallContext) -> Result<JsExternal> {
|
|
|
|
let count = ctx.get::<JsNumber>(0)?.try_into()?;
|
|
|
|
let native = NativeObject { count };
|
|
|
|
ctx.env.create_external(native, Some(5))
|
|
|
|
}
|
|
|
|
|
2020-06-21 19:10:06 +08:00
|
|
|
#[js_function(1)]
|
|
|
|
pub fn get_external_count(ctx: CallContext) -> Result<JsNumber> {
|
|
|
|
let attached_obj = ctx.get::<JsExternal>(0)?;
|
|
|
|
let native_object = ctx.env.get_value_external::<NativeObject>(&attached_obj)?;
|
|
|
|
ctx.env.create_int32(native_object.count)
|
|
|
|
}
|
2020-09-02 17:05:53 +08:00
|
|
|
|
2020-11-25 17:42:14 +08:00
|
|
|
pub fn register_js(exports: &mut JsObject) -> Result<()> {
|
|
|
|
exports.create_named_method("createExternal", create_external)?;
|
2021-03-11 19:02:42 +08:00
|
|
|
exports.create_named_method("createExternalWithHint", create_external_with_hint)?;
|
2020-11-25 17:42:14 +08:00
|
|
|
exports.create_named_method("getExternalCount", get_external_count)?;
|
2020-09-02 17:05:53 +08:00
|
|
|
Ok(())
|
|
|
|
}
|