2020-06-21 20:10:06 +09:00
|
|
|
use std::convert::TryInto;
|
|
|
|
|
2020-11-25 18:42:14 +09:00
|
|
|
use napi::{CallContext, JsExternal, JsNumber, JsObject, Result};
|
2020-06-21 20:10:06 +09: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 12:57:26 +09:00
|
|
|
ctx.env.create_external(native, None)
|
2020-06-21 20:10:06 +09:00
|
|
|
}
|
|
|
|
|
2021-03-11 20:02:42 +09: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 20:10:06 +09: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 18:05:53 +09:00
|
|
|
|
2020-11-25 18:42:14 +09:00
|
|
|
pub fn register_js(exports: &mut JsObject) -> Result<()> {
|
|
|
|
exports.create_named_method("createExternal", create_external)?;
|
2021-03-11 20:02:42 +09:00
|
|
|
exports.create_named_method("createExternalWithHint", create_external_with_hint)?;
|
2020-11-25 18:42:14 +09:00
|
|
|
exports.create_named_method("getExternalCount", get_external_count)?;
|
2020-09-02 18:05:53 +09:00
|
|
|
Ok(())
|
|
|
|
}
|