快速上手

5 分钟完成 TypeScript 与 Rust 双向 FFI 项目

1

环境准备

确保已安装以下工具:

  • Node.js >= 18
  • Rust stable(rustup)
sh
npm install -g @tsffib/cli
2

创建项目

使用 CLI 初始化一个双向 FFI 模板项目:

sh
tsffib init hello-tsffi --template=bidirectional
3

编写 Rust 代码

src/lib.rs 中使用注解宏定义导出函数和回调:

rust
// 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))
}
4

编写 TypeScript 代码

TypeScript 端直接调用,类型定义已自动生成:

ts
// __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)
5

运行

安装依赖、构建原生模块、运行测试:

sh
cd hello-tsffi
npm install
npx napi build --js false
node __tests__/index.ts
6

更多模板

探索其他项目模板:

sh
tsffib template

可用模板包括 minimal-bidirectional、async-progress、struct-callback、error-handling 等。