diff --git "a/src/rust-learn/napi-rs/5.\346\212\212JS \345\207\275\346\225\260\346\224\276\345\210\260 Rust \344\270\255\346\211\247\350\241\214.md" "b/src/rust-learn/napi-rs/5.\346\212\212JS \345\207\275\346\225\260\346\224\276\345\210\260 Rust \344\270\255\346\211\247\350\241\214.md" new file mode 100644 index 0000000000..99362f1ba0 --- /dev/null +++ "b/src/rust-learn/napi-rs/5.\346\212\212JS \345\207\275\346\225\260\346\224\276\345\210\260 Rust \344\270\255\346\211\247\350\241\214.md" @@ -0,0 +1,27 @@ +# 把JS 函数放到 Rust 中执行 + + +```rust +use std::thread; + +use napi::{ + bindgen_prelude::*, + threadsafe_function::{ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode}, +}; + +// 强制指定参数类型 +#[napi(ts_args_type = "callback: (err: null | Error, result: number) => void")] +pub fn call_threadsafe_function(callback: JsFunction) -> Result<()> { + let tsfn: ThreadsafeFunction = callback + // ctx.value 即 Rust 调用 JS 函数时传递的入参,封装成 Vec 传递给 JS 函数 + .create_threadsafe_function(0, |ctx| ctx.env.create_uint32(ctx.value).map(|v| vec![v]))?; + for n in 0..100 { + let tsfn = tsfn.clone(); + thread::spawn(move || { + // 通过 tsfn.call 来调用 JS 函数 + tsfn.call(Ok(n), ThreadsafeFunctionCallMode::Blocking); + }); + } + Ok(()) +} +``` \ No newline at end of file