跳到正文
教程首页
Dart + FFICH 10ch10_ffi

ch10-ffi

FFI 实战:用 dart:ffi 调用 C / Rust / Go 原生库。完整工程共 22 个文件,其中 22 个文本源文件可在下面在线阅读。

22

在线文本文件

1,514

源码行数

dart / go / c

语言

22 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

darttextcrustmarkdown

22 text files · 1,514 lines

rustnative/rust/src/lib.rs
//! ch10 · Rust 侧:`extern "C"` + `#[no_mangle]` 导出 C ABI。
//!
//! Rust 的默认 ABI 是不稳定的 Rust ABI,Dart 无法调用;
//! 必须显式声明 `extern "C"` 并禁止名字修饰(`#[no_mangle]`)。

use std::ffi::{CStr, CString};
use std::os::raw::c_char;

/// 数值:基本传参与返回值。
#[no_mangle]
pub extern "C" fn add_i32(a: i32, b: i32) -> i32 {
    a.wrapping_add(b)
}

#[no_mangle]
pub extern "C" fn mul_f64(a: f64, b: f64) -> f64 {
    a * b
}

/// 字符串:入参是 `*const c_char`(Dart 侧 toNativeUtf8 分配),
/// 返回值由 `CString::into_raw` 交给调用方,必须用 `free_string` 归还。
#[no_mangle]
pub extern "C" fn concat_strings(a: *const c_char, b: *const c_char) -> *mut c_char {
    if a.is_null() || b.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 调用方保证指针指向合法的 NUL 结尾字符串。
    let left = unsafe { CStr::from_ptr(a) }.to_string_lossy();
    let right = unsafe { CStr::from_ptr(b) }.to_string_lossy();
    match CString::new(format!("{left}{right}")) {
        Ok(s) => s.into_raw(),
        Err(_) => std::ptr::null_mut(),
    }
}

/// SAFETY: `s` 必须来自 `concat_strings`(即 `CString::into_raw` 的产物),且只能释放一次。
#[no_mangle]
pub unsafe extern "C" fn free_string(s: *mut c_char) {
    if !s.is_null() {
        drop(CString::from_raw(s));
    }
}

/// 回调:直接接收 C 函数指针并调用。
#[no_mangle]
pub extern "C" fn apply_cb(cb: extern "C" fn(i32) -> i32, x: i32) -> i32 {
    cb(x)
}

代码构成:dart 24 KB · text 14 KB · c 2 KB · rust 2 KB

本地运行

zip → 解压 → 执行
$cd examples/ch10-ffi/native && ./build_all.sh
$cd examples/ch10-ffi && dart pub get && dart run

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • dart analyze 0 告警、dart test 18 个用例全绿(C 手写绑定 / C ffigen 生成绑定 / Rust / Go)
查看全部示例