用途:帮助在 Rust 中安全地进行跨语言调用与导出,涵盖调用 C/C++ 代码、将 Rust 导出为 C 头文件、以及 Python、Java、Node.js 等语言扩展。
主要能力:
- 绑定生成:C/C++ 到 Rust 用 bindgen(bindgen input.h --output src/bindings.rs --allowlist-type 'my_' --allowlist-function 'my_');Rust 到 C 用 cbindgen(cbindgen --crate mylib --output include/mylib.h)。
- 常见模式:调用 C 函数用 extern "C" 加 #[link];字符串用 CStr/CString;回调函数使用 extern "C" ABI;C++ 用 cxx 的 #[cxx::bridge]。
- 类型映射:如 i32 对应 int、usize 对应 uintptr_t、const T 对应 const T、&CStr 对应 const char*、NonNull<T> 对应 T*、Option<NonNull<T>> 对应可空 T*。
- 错误与 panic 处理:C 错误码转 Result;跨 FFI 的 panic 属未定义行为,需用 std::panic::catch_unwind 捕获;C++ 异常在 FFI 边界捕获。
- 内存管理:明确谁分配谁释放,Rust 分配用 Vec 加 std::mem::forget 交出所有权,配套 free_buffer 用 Vec::from_raw_parts 释放。
- 工作流:选择 FFI 策略、定义安全不变量、构建安全封装层(unsafe 调用 → 私有安全函数 → 公开安全 API)、充分测试。
- 工具与语言:Python 用 PyO3、Java 用 jni、Node.js 用 napi-rs、C# 用 csharp-bindgen、Go 用 cgo、C++ 用 cxx。
- 验证命令:cargo +nightly miri test、valgrind --leak-check=full ./target/release/program、bindgen wrapper.h --output src/ffi.rs、cbindgen --lang c --output target/mylib.h、nm target/release/libmylib.so | grep my_function。
适用场景:需要 Rust 与 C/C++ 或其他语言互操作、审查 FFI 代码安全性、排查内存与 ABI 问题。
限制与注意:跨 FFI panic 属 UB,必须 catch_unwind;类型需 #[repr(C)];导出函数需 #[no_mangle];原始指针需先验证再解引用;建议用 Miri 检测 UB。未提供官方收费、平台支持范围等信息。