5 分钟完成 TypeScript 与 Rust 双向 FFI 项目
确保已安装以下工具:
npm install -g @tsffib/cli使用 CLI 初始化一个双向 FFI 模板项目:
tsffib init hello-tsffi --template=bidirectional在 src/lib.rs 中使用注解宏定义导出函数和回调:
// src/lib.rs
use tsffi::prelude::*;
#[tsffi::callback]
fn on_progress(pct: f64) -> bool {
println!("进度: {}%", pct);
pct < 100.0
}
#[tsffi::export]
fn process_file(path: String) -> Result<String> {
let data = fs::read_to_string(&path)?;
Ok(transform(&data))
}TypeScript 端直接调用,类型定义已自动生成:
// __tests__/index.ts
import { processFile, onProgress } from '../index'
onProgress((pct: number) => {
console.log(`进度: ${pct}%`)
return pct < 100
})
const result = processFile('./input.txt')
console.log(result)安装依赖、构建原生模块、运行测试:
cd hello-tsffi
npm install
npx napi build --js false
node __tests__/index.ts探索其他项目模板:
tsffib template可用模板包括 minimal-bidirectional、async-progress、struct-callback、error-handling 等。