跳到正文
教程首页
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

gonative/go/add.go
// ch10 · Go 侧:`-buildmode=c-shared` + `//export` 导出 C ABI。
package main

/*
#include <stdint.h>
#include <stdlib.h>

typedef int32_t (*cb_t)(int32_t);

// cgo 不能直接把 uintptr 转成函数指针调用,必须借一层 C 函数。
static int32_t invoke_cb(uintptr_t p, int32_t x) { return ((cb_t)p)(x); }
*/
import "C"

import "unsafe"

//export AddI32
func AddI32(a, b C.int32_t) C.int32_t {
	return a + b
}

//export MulF64
func MulF64(a, b C.double) C.double {
	return a * b
}

// ConcatStrings 用 C.CString 分配(malloc),由 FreeString 释放。
//
//export ConcatStrings
func ConcatStrings(a, b *C.char) *C.char {
	return C.CString(C.GoString(a) + C.GoString(b))
}

//export FreeString
func FreeString(s *C.char) {
	C.free(unsafe.Pointer(s))
}

//export ApplyCb
func ApplyCb(cb C.uintptr_t, x C.int32_t) C.int32_t {
	return C.invoke_cb(cb, x)
}

func main() {}

代码构成: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)
查看全部示例