#1.7. FFI:extern "C" / CStr / CString / CPtr
本页内容
- 1.7.1. extern "C" 块
- #[link("name")]:指定库
- 调用约定
- #[leaf]:短调用
- str 参数与返回值
- C 编译器与平台 ABI
- 1.7.2. CStr / CString:以 null 结尾的字符串
- CString:拥有所有权、以 null 结尾
- 示例:strlen
- 1.7.3. CPtr<T> 与可空性
- 1.7.4. using 块:RAII
- 1.7.5. 安全包装模式:分离 sys 与安全层
- 1.7.6. 自动生成绑定
- bindgen 读取的 C
- 1.7.7. 调用安全责任的划分
- 1.7.8. 与其他语言的比较
- 1.7.9. C 类型:c_int、c_long、c_void
- 1.7.10. Handle<T>:C 持有的 Nabi 值
- 1.7.11. #[errno]:errno 与 GetLastError
- 1.7.12. WideCStr / WideCString:wchar_t 字符串
- 1.7.13. Library:加载共享库
bare::ffi 模块提供定义与 C ABI 兼容的外部函数和数据的机制。它与 refs-lang 5.9 extern 块 定义的 extern "C" { ... } 块配合使用。
除了 CStr / CString,该模块还包含 C 的类型(types,也在 prelude 中,1.7.9)、供 C 持有 Nabi 值的 Handle(1.7.10)、保存的 errno(1.7.11)、wchar_t 字符串(1.7.12),以及用于加载共享库的 Library(1.7.13)。
本章只介绍传统的 C FFI;基于 WASM 组件模型(Component Model)的 FFI 另见 1.8 wit。
#1.7.1. extern "C" 块
最基本的形式如下:
extern "C" {
// function declarations
fn malloc(size: usize) -> CPtr<u8>;
fn free(ptr: CPtr<u8>);
fn strlen(s: ConstPtr<c_char>) -> usize;
// global (read-only)
static environ: CPtr<CPtr<c_char>>;
// global (mutable): the `mut` keyword is allowed _only here_
static mut atexit_count: u64;
}
C 的 errno 不是全局变量,而是按线程区分的宏,因此不能声明为 static;#[errno] 会在调用后保存它(1.7.11)。C 的整数类型用它们的 C 名称书写(c_int、c_long、c_size_t,1.7.9),这些名称在每个目标上都有正确的大小。
这里出现的 mut 关键字在 refs-lang 1.5 关键字 中定义,只在这个位置有意义,不能用于普通变量。
##[link("name")]:指定库
要显式指定库,使用 #[link] 属性。
#[link("c")]
extern "C" {
fn malloc(size: usize) -> CPtr<u8>;
fn free(ptr: CPtr<u8>);
}
#[link("m")]
extern "C" {
fn cos(x: f64) -> f64;
fn sin(x: f64) -> f64;
}
链接器会自动加上 -lc 或 -lm 等标志。
#调用约定
C 代码可以指名两种调用约定;"nabi" 是运行时 ABI(refs-lang 5.9.2)。其他 ABI 字符串都是错误(E0025)。
extern "C" { ... } // System V (Unix) / Microsoft x64 (Windows)
extern "system" { ... } // Windows: stdcall on x86, C on x64 / aarch64
对大多数用户来说,默认的 "C" 就足够了。"system" 主要在处理 Windows API 时出现。
##[leaf]:短调用
#[leaf]
extern "C" {
fn abs(x: c_int) -> c_int;
fn labs(x: c_long) -> c_long;
}
每次 extern "C" 调用都会让调用线程进入停驻状态:C 运行期间,该线程对回收器而言视为已停止,因此调用期间可能进行回收(1.7.7,refs-lang 8.4.10)。在块或单个声明上写 #[leaf] 会省去这一对包围操作,使短调用的开销更低。leaf 函数必须很快返回,不得阻塞(锁、I/O、睡眠),也不得回调 Nabi:它运行期间,该线程会推迟进程中的所有回收,所以阻塞的 leaf 函数会让每个进行分配的线程停滞。调试版工具链会检查线程在 leaf 调用内部从不为回收而停止。在 extern "nabi" 块上写 #[leaf] 是错误(1.7.11)。
#str 参数与返回值
extern "C" 函数的 str 参数以 NUL 结尾的 char* 传递(refs-lang 5.9.4)。str 结果是错误,因为返回的 char* 的字节归 C 所有:应当把它声明为 ConstPtr<c_char> | none,再用 CStr::from_ptr 复制(1.7.2)。(ptr, len) 形式的传递属于运行时 ABI extern "nabi"(5.9.2)。
extern "C" {
fn puts(s: str) -> i32; // "hi" → NUL-terminated char*
fn getenv(name: str) -> CPtr<c_char>; // may be null; received as CPtr
}
#C 编译器与平台 ABI
每个目标的 C ABI 就是该平台的 ABI 文档:System V psABI(x86-64、i386)、AAPCS64、带 VFP 的 AAPCS32、RISC-V psABI、ELFv2、s390x ELF ABI、WebAssembly C ABI,以及 Microsoft 的 x64 / x86 / ARM64 约定。工具链的测试依据生成的签名表(结构体、联合体、同构浮点聚合、f16 / bf16、Simd、超对齐结构体和紧凑结构体、寄存器耗尽、可变参数尾部、各种大小的结果、两个方向),把每个目标与构建其库的 C 编译器对照检查:Linux 上的 gcc 15.2 和 clang 21(x86-64、i686、aarch64;armv7、riscv64、powerpc64le 和 s390x 用 clang,测试机器上没有它们的交叉 gcc),macOS 上的 Apple clang 21,Windows x64 和 i686 上的 MSVC 14.44(cl,作为基准)和 clang-cl 22,Windows ARM64 上的 MSVC 14.44 和 clang。
编译器之间有分歧时,以文档为准:
- 聚合中的 AArch64
__bf16:AAPCS64 把它算作半精度浮点数,因此由__bf16组成的结构体是放在v寄存器中的同构浮点聚合,与 clang 的传递方式一致。gcc 15.2 在整数寄存器中传递这种结构体;C 库由 gcc 构建时,应当把 C 一侧声明为uint16_t字段。 - i686 上的
f16/bf16:gcc 只在启用 SSE2(-msse2,即 nabi 的 i686 目标所假定的基线)时传递_Float16,与 clang 一致。 - MSVC 按超对齐成员的对齐方式布局包含该成员的紧凑结构体;nabi 在
*-windows-msvc目标上也这样做,在其他目标上使用 GNU 布局。
不涵盖:宽于 8 字节的 long double、__int128 和 _Complex(没有 nabi 形式)、C++ 空结构体(C 中没有)。
#1.7.2. CStr / CString:以 null 结尾的字符串
CStr 是处理 C 字符串的借用类型。
struct CStr {
// internal: the bytes and the final NUL in one str object
}
impl CStr {
unsafe fn from_ptr(p: ConstPtr<c_char>) -> CStr | none;
// copies up to the NUL; null pointer → none
// p must be null or point at a live NUL-terminated string
fn from_bytes_with_nul<B: AsBytes>(bytes: B) throws (FromBytesWithNulError) -> CStr;
// checked: last byte is 0, no interior 0
fn from_bytes_until_nul<B: AsBytes>(bytes: B) throws (FromBytesUntilNulError) -> CStr;
// the bytes before the first 0 (a fixed C buffer)
fn as_ptr(self) -> ConstPtr<c_char>;
fn as_bytes(self) -> Slice<u8>; // excluding the null terminator
fn as_bytes_with_nul(self) -> Slice<u8>; // including the null terminator
fn to_str(self) throws (Utf8Error) -> str; // UTF-8 conversion
fn len(self) -> usize; // excluding the null terminator
}
from_ptr 把 C 字符串复制进来,直到它的 NUL,因此结果总是有效的 C 字符串。它是 unsafe fn:悬垂指针,或指向不含 NUL 的字节的指针,都是未定义行为。每个构造函数都会复制,所以检查字节不会带来额外开销,也就没有不检查的形式;from_bytes_until_nul 读取定长的 C 缓冲区,其中 NUL 之后的尾部是无用数据。CStr / CString 把字节和 NUL 保存在同一个 GC 对象中;as_ptr 的有效范围与 str::as_ptr 相同(2.15.2):在可能出现指针值的函数中,持有该 CStr / CString 的变量处于作用域内的期间。
#CString:拥有所有权、以 null 结尾
需要拥有所有权的形式时,使用 CString。
struct CString { /* GC heap, null-terminated */ }
impl CString {
fn new<B: AsBytes>(bytes: B) throws (NulError) -> CString;
// rejects interior null bytes; a str gives its UTF-8
fn as_c_str(self) -> CStr;
fn as_ptr(self) -> ConstPtr<c_char>;
fn into_bytes(self) -> List<u8>; // owned bytes (excluding null)
fn into_bytes_with_nul(self) -> List<u8>;
}
错误类型会说明字节在哪里出错;每个错误类型都实现 Display(即其 message())、Debug、Error、PartialEq、Eq 和 Clone,NulError 的字段是私有的(0.5.10)。
struct NulError { .. }
impl NulError {
fn position(self) -> usize; // index of the interior NUL (CString::new)
fn message(self) -> str; // "nul byte found at position 1"
}
enum FromBytesWithNulError { // CStr::from_bytes_with_nul
InteriorNul { position: usize; }, // a NUL before the last byte
NotNulTerminated, // the last byte is not a NUL
}
impl FromBytesWithNulError {
fn message(self) -> str; // "interior nul byte at 3"
}
struct FromBytesUntilNulError; // no NUL at all (CStr::from_bytes_until_nul); message()
#示例:strlen
extern "C" {
fn strlen(s: ConstPtr<c_char>) -> usize;
}
let s: str = "hello";
let cs = try CString::new(s);
let n = unsafe { strlen(cs.as_ptr()) }; //→ 5
说明
str 与 CStr 之间的转换需要一次分配(必须加上 null 终止符)。str 通常不以 null 结尾,因此建议只在 FFI 调用处显式转换。
#1.7.3. CPtr<T> 与可空性
权威定义见 1.1.5 CPtr。C 函数返回 T* 时,必须明确写出可能为 null,这时使用的就是这个类型。
extern "C" {
fn fopen(path: ConstPtr<c_char>, mode: ConstPtr<c_char>) -> CPtr<FILE>;
fn fclose(file: CPtr<FILE>) -> i32;
}
struct FILE; // opaque
let path = try CString::new("data.txt");
let mode = try CString::new("r");
let f: CPtr<FILE> = unsafe { fopen(path.as_ptr(), mode.as_ptr()) };
match f.as_ptr() {
file: Ptr<FILE> => {
// use
unsafe { fclose(f) };
}
none => panic("fopen failed"),
}
#1.7.4. using 块:RAII
GC 不运行终结器,因此外部资源由 Drop 释放,编译器在固定的位置调用它:值的所有者离开作用域的地方(每条退出路径上),或绑定该值的 using 块结束的地方(2.13.4)。bare::ffi 没有自己的文件 API:下面的包装类型自行声明 C 函数,并在 Drop 中关闭句柄。
struct FILE; // opaque (1.7.3)
#[link("c")]
extern "C" {
fn fopen(path: ConstPtr<c_char>, mode: ConstPtr<c_char>) -> CPtr<FILE>;
fn fclose(file: CPtr<FILE>) -> i32;
}
// a user-written owner of the C handle; Drop closes it
struct File { raw: CPtr<FILE>; }
impl Drop for File {
fn drop(ref self) { unsafe { fclose(self.raw) }; }
}
fn open(path: str) -> File {
let p = try! CString::new(path);
let m = try! CString::new("r");
let raw = unsafe { fopen(p.as_ptr(), m.as_ptr()) };
if raw.is_null() { panic("fopen failed"); }
File { raw }
}
using f = open("data.txt") {
process(f);
} // ← automatic fclose at end of scope (Drop)
// without using: released where `f` leaves scope
fn run() throws {
let f = open("data.txt");
try process(f); // an error propagating out also runs fclose
} // ← fclose here (Drop)
using 语法本身由 refs-lang 3.17 using 表达式 规定,并与 2.13 marker 的 Drop trait 集成工作。
#1.7.5. 安全包装模式:分离 sys 与安全层
Rust 生态中的标准做法是把 *-sys crate(原始 FFI)与同名 crate(安全包装)分开。Nabi 推荐同样的模式。
// libc-sys module: raw FFI
mod c {
#[link("c")]
extern "C" {
pub fn malloc(size: usize) -> CPtr<u8>;
pub fn free(ptr: CPtr<u8>);
pub fn strdup(s: ConstPtr<c_char>) -> CPtr<c_char>;
}
}
// libc: safe wrapper
pub struct AllocError { pub size: usize; }
pub fn alloc_buffer(size: usize) throws (AllocError) -> List<u8> {
let p = unsafe { c::malloc(size) };
match p.as_ptr() {
ptr: Ptr<u8> => {
// unsafe → safe boundary
let bytes = unsafe { ptr.as_many().slice(size).to_list() };
unsafe { c::free(p) };
bytes
}
none => { throw AllocError { size }; }
}
}
这种分离把不安全代码限制在很小的范围内。用户代码只调用安全包装,从而保证安全。
#1.7.6. 自动生成绑定
nabi bindgen(refs-lang 9.10.8)从 C 头文件生成 Nabi 声明。它用工具链的 C 编译器 nabicc(refs-lang 9.13)的前端读取头文件,该前端按目标的 C 编译器的方式对 C 进行预处理、解析和布局;不需要其他 C 编译器,也不需要 libclang。
nabi bindgen libfoo.h > libfoo_sys.nabi
nabi bindgen libfoo.h --target=x86_64-pc-windows-msvc -o libfoo_sys.nabi -- -I include -DFOO=1
输出针对单个目标(--target,默认为主机):大小、布局和整数位宽都是该目标 C ABI 的。-- 之后的实参是 C 编译器选项(refs-lang 9.10.8)。对本机自己的平台、Apple 目标(SDK),以及 MSVC 主机上的 MSVC 目标(INCLUDE,否则使用最新的 Visual Studio 和 Windows SDK),使用本机的系统头文件;对其他目标,除非在 -- 之后给出 --sysroot,否则只使用编译器的内置头文件(stddef.h、stdint.h、stdarg.h、stdbool.h、limits.h、float.h 等),目标的头文件在 -- 之后传入(-isystem <dir>)。输出的内容包括该头文件及其包含的非系统头文件的声明(对于系统目录中的头文件,还包括它从自身目录树中包含的头文件的声明),以及它们用到的其他头文件中的声明。前端拒绝的头文件是错误(退出码 1),报告在其 file:line:col 处。
映射约定如下:
- C 的整数和浮点类型变为目标上同样大小的 Nabi 基本类型(
int→i32,long→i32或i64,char→c_char,_Bool→bool,_Float16→f16,__bf16→bf16);size_t/uintptr_t→usize,ssize_t/intptr_t/ptrdiff_t→isize。系统头文件中对这类类型的 typedef 就是该类型本身。 - typedef 变为 Nabi 类型别名。
- 结构体和联合体映射为
#[repr(C)] struct/union(目标的布局需要时为#[repr(C, align(N))]或#[repr(packed)])。一串连续的位域变为一个覆盖其存储的字节数组字段_bitfieldN。Nabi 无法表达的布局(N > 1 的#pragma pack(N)、联合体中的位域)变为大小和对齐相同、包含_opaque: [u8; N]的结构体。只声明未定义的结构体变为struct Name;(不透明)。 - 枚举变为其整数类型的别名,外加每个枚举项一个
const(pub type color = u32; pub const RED: color = 0;);匿名枚举只生成它的常量。 - 对象指针(
T*、const T*)变为CPtr<T>;void*变为CPtr<u8>。 - 数组参数按 C 的调整规则视为指针(
char buf[16]→CPtr<c_char>),函数类型的参数视为函数指针。 - 函数变为
extern "C" fn(C 的可变参数函数,以及未带原型声明的函数(f()):...);32 位 x86 Windows 上的 stdcall 函数放入extern "system"。全局变量变为static(非 const 时为static mut)。静态函数和内联函数被跳过(没有可链接的符号)。 - 函数指针变为
unsafe extern "C" fn(...) -> R | none(refs-lang 5.9.4;NULL =none)。 - 求值为整数、浮点或字符串常量的类对象宏变为
const项。 - 与 Nabi 关键字或基本类型名相同的 C 名称会加上结尾的
_;函数和静态变量通过#[link_name]保留其 C 符号。 - 其他内容(128 位整数、
__fp16、宽于 8 字节的long double、向量和块类型、可变参数函数指针、线程局部变量、其他调用约定)会被跳过,并留下// skipped ...注释。写成字节形式(_opaque)的结构体从不按值传递:直接或在其他结构体内部接受或返回它的函数或函数指针会被跳过,因为 C 按其字段对它分类。
#bindgen 读取的 C
前端读取 C17 以及系统头文件使用的扩展,与 clang 对该目标的处理一致:
- 预处理器:目标的预定义宏(
__x86_64__、_WIN32、__APPLE__、__SIZEOF_LONG__,MSVC 目标上的_MSC_VER和其他目标上的__GNUC__等)、#include、#include_next、__has_include、带defined、__has_attribute、__has_builtin和__has_feature的#if算术、带#、##、__VA_ARGS__和__VA_OPT__的类对象宏和类函数宏、_Pragma/__pragma,以及#pragma pack、once、push_macro/pop_macro;其他 pragma 被忽略。 - 带有
__attribute__((..))、__declspec(..)、[[..]]、__asm__("symbol")标签、可空性限定符、__extension__、typeof、_Alignas、_Atomic、_Static_assert的声明,匿名结构体和联合体、位域、柔性数组成员、指定底层类型的枚举、块指针(^)和向量类型。函数体和初始化器被跳过(nabicc会读取并编译它们,refs-lang 9.13)。 - 代替 clang 自带头文件的内置头文件(
stddef.h、stdint.h、stdarg.h、stdbool.h、limits.h、float.h等),其中包括内建函数头文件:x86 上的immintrin.h、x86intrin.h以及mmintrin.h..nmmintrin.h、wmmintrin.h系列(MMX 到 SSE4.2、AVX、AVX2、FMA、F16C、BMI、BMI2、LZCNT、POPCNT、AES、PCLMUL 和 CRC32,以原型形式提供;AVX-512 和 AMX 的类型不带其函数),Arm 上的arm_neon.h、arm_acle.h、arm_fp16.h和arm_bf16.h,以及 MSVC 目标上的intrin.h(x86 上还有x86intrin.h)。每个内建函数都是没有函数体的声明,从不绑定;向量类型(__m128、__m256i、float32x4_t等)如上所述被跳过,包含它们的结构体变为字节形式。在其他架构上包含这类头文件是错误,与 clang 一致(在 Arm 上#include <immintrin.h>)。 - 按目标规则进行的记录布局:System V 或 Microsoft 位域、
#pragma pack、packed、aligned、__declspec(align)、mode。 - 由整数、浮点、字符和字符串字面量、枚举常量、强制转换、
sizeof、_Alignof、offsetof(__builtin_offsetof或&((T *)0)->m)以及算术、位、比较、逻辑和条件运算符构成的常量表达式(数组大小、枚举值、位宽、对齐、_Static_assert、宏的值)。
无论 -std= 如何指定,方言都是 GNU C17。它不能读取的内容会在其 file:line:col 处报错,并说明应当改写成什么:
| 构造 | 改写为 |
|---|---|
K&R 风格的函数定义(int f(a, b) int a; ..) | 原型:int f(int a, int b) |
隐式 int(static x;) | 写出类型:static int x; |
无法求值的数组大小、枚举值、位宽或对齐(其他 __builtin_ 调用、_Generic、语句表达式) | 由上述形式构成的整数常量表达式 |
| 未知的类型名 | 在使用之前写出它的声明,或 #include 声明它的头文件 |
| 找不到的头文件 | 在 -- 之后写 -I <dir> / -isystem <dir>;对于不是本机平台的目标,传入它的头文件(-isystem <dir> 或 --sysroot <dir>) |
#1.7.7. 调用安全责任的划分
在调用处各项由谁负责:
| 项目 | 责任方 |
|---|---|
| 指针的 null 检查 | Nabi 代码(C → Nabi 方向) |
| 缓冲区长度验证 | Nabi 代码(必须知道长度) |
| 字符串的 null 终止 | 创建 CString 时自动完成 |
| GC 固定 | Nabi 代码,对它传给 C 的每个指向 GC 对象内部的指针(1.6.5) |
| C 保留的 Nabi 值 | Nabi 代码,通过 Handle(1.7.10) |
释放内存(free) | Nabi 代码或安全包装 |
| 调用约定的匹配 | extern 声明者 |
| C 类型的大小 | extern 声明者,使用 c_* 名称(1.7.9) |
| 线程安全 | 遵循 C 库的文档 |
| Errno / GetLastError | 声明上的 #[errno](1.7.11) |
| C 调用的函数中发生 panic | 运行时中止程序,或返回 #[on_panic] 的值(refs-lang 5.9.12) |
每次 extern "C" 调用都会让线程进入停驻状态(1.7.1),因此任何 C 调用期间都可能进行回收,无论调用多短。指向 GC 对象内部的指针(列表的缓冲区、StrBuf 的字节)只有在对象被固定时才在调用期间有效;str 实参是唯一的例外,因为它的根使它保持在原位(1.6.5)。编译器不会自行省略任何固定。
#1.7.8. 与其他语言的比较
扩大比较范围,Nabi 的定位会更清楚。
| 方面 | C | Rust | Zig | Go | Nabi |
|---|---|---|---|---|---|
| 外部函数 | (直接) | extern "C" { ... } | extern "..." | import "C"(cgo) | extern "C" { ... } |
| 调用约定 | (一个默认) | extern "system" 等 | extern "C" 等 | 只有 "C" | "C" / "system" |
| C 字符串 | char* | CStr / CString | [*:0]u8 | C.CString / C.GoString | CStr / CString |
| 可空指针 | (默认) | Option<*const T> | ?*T | *C.struct_T(总是可空) | CPtr<T> |
| 绑定工具 | 无 | bindgen / cbindgen | @cImport | cgo | nabi bindgen |
| C 源代码 | (编译器本身) | 外部 C 编译器(cc crate) | zig cc(内置) | 外部 C 编译器(cgo) | nabi cc / 清单中的 c(内置) |
| C 类型 | (原生) | core::ffi::c_int 等 | c_int 等 | C.int 等 | c_int 等(prelude) |
| GC 固定 | 不适用 | 不适用 | 不适用 | runtime.Pinner(1.21+) | bare::gc::pin |
| C 持有的值 | (直接) | Box::into_raw | (直接) | runtime/cgo.Handle | bare::ffi::Handle |
| 运行时加载 | dlopen | (crate) | std.DynLib | (无) | bare::ffi::Library |
| RAII / using | (手动) | Drop | defer | defer | using 块(Drop) |
Nabi 最大的不同可以归结为三点。
- GC 与 FFI 的集成。把
Pinned<T>守卫与using块结合使用,可以同时防止资源泄漏和遗漏固定。 - 严格的指针模型。
Ptr<T>/ConstPtr<T>/ManyPtr<T>/CPtr<T>彼此分开(1.1)。 - 强制安全包装。
as强制转换会被拒绝,只允许具名的强制转换(1.2)。
#1.7.9. C 类型:c_int、c_long、c_void
bare::ffi::types 按目标 C 编译器确定的大小为 C 的整数和浮点类型命名。prelude 包含全部这些名称,所以声明时不需要 use。
| 名称 | C 类型 | Nabi 类型 |
|---|---|---|
c_schar / c_uchar | signed char / unsigned char | i8 / u8 |
c_short / c_ushort | short / unsigned short | i16 / u16 |
c_int / c_uint | int / unsigned int | i32 / u32 |
c_long / c_ulong | long / unsigned long | 在 Windows 和 32 位目标上为 i32 / u32;其他目标上为 i64 / u64 |
c_longlong / c_ulonglong | long long / unsigned long long | i64 / u64 |
c_size_t / c_ssize_t | size_t / ssize_t | usize / isize |
c_ptrdiff_t | ptrdiff_t | isize |
c_intptr_t / c_uintptr_t | intptr_t / uintptr_t | isize / usize |
c_wchar | wchar_t | Windows 上为 u16;Linux 的 arm 和 aarch64 上为 u32;其他目标上为 i32 |
c_float / c_double | float / double | f32 / f64 |
c_void | 指针后面的 void | 空结构体 |
c_char 是单独的语言类型(2.15.5)。
每个名称都是类型别名(pub type c_int = i32;),通过 #[cfg] 按目标选定:在同一目标上,c_int 和 i32 是同一个类型,值在二者之间传递无须转换。定长类型只有在与 C 的类型一致时才正确:fn labs(x: i64) -> i64 在 64 位 Linux 和 macOS 上正确,在 Windows 上则是错的,因为那里的 long 是 32 位。用 c_long 书写,声明就在每个目标上都成立。
c_void 是一个空结构体,表示指针后面的 C void:CPtr<c_void> 是 void*,ConstPtr<c_void> 是 const void*。不会创建或读取 c_void 值。
extern "C" {
fn labs(x: c_long) -> c_long;
fn strlen(s: str) -> c_size_t;
}
let x: c_long = -3;
println(f"{unsafe { labs(x) }} {unsafe { strlen("abc") }}"); //→ 3 3
let p: CPtr<c_void> = CPtr::null(); // a null void*
#1.7.10. Handle<T>:C 持有的 Nabi 值
需要回调的 C API 会接受一个 void* user_data 并把它传给回调。Handle<T> 通过这个指针携带 Nabi 值。
// bare::ffi
#[repr(transparent)]
struct Handle<T> { /* a handle number, pointer-sized */ }
impl<T> Copy for Handle<T> {}
impl<T> Handle<T> {
fn new(value: T) -> Handle<T>; // keeps value alive and in place until the last release
unsafe fn from_ptr(p: CPtr<c_void>) -> Handle<T>; // the handle C passed back
fn as_ptr(self) -> CPtr<c_void>; // the void* to pass to C
fn get(self) -> T; // the value
fn set(self, value: T); // replaces the value every copy of the handle sees
fn retain(self); // one more release before the value is let go
fn release(self); // lets the value go after as many releases as new and retains
}
Handle::new 把值放进一个由句柄作为根并固定的 GC 单元:在最后一次 release 之前,无论 C 持有指针期间进行了多少次回收,值都保持存活并保持其地址不变。对于 List、Dict 或其他共享值,get 返回同一个对象,所以向列表 push 的回调会改变调用方的列表;普通值(整数、结构体)会被复制出来。retain 用于保留指针第二份副本的 C 代码:每次 retain 都需要多一次 release。
该指针是句柄编号,从不为 null,也从不是地址:C 不得通过它读取。Handle<T> 是 Copy 的、指针大小的,并且是基于 CPtr<c_void> 的 #[repr(transparent)],因此可以作为 #[repr(C)] 结构体的字段。它实现 Clone 和 Debug。
from_ptr 是 unsafe 的:p 必须来自 Handle::<T>::new(..).as_ptr()。get、set、retain 和 release 会检查句柄,句柄不正确时触发 panic:
- 在最后一次
release之后(或不是句柄的值):handle already released (or not a handle): call `release` once per `Handle::new` and `retain`, and not `get` after the last one - 类型与创建时不同:
this handle holds `List<str>`, not `Dict<str, i64>`: write `Handle::<List<str>>::from_ptr(p)`
闭包与其他值一样是值。它自身的类型无法写出,所以按 fn 类型存储:Handle::<fn(c_int)>::new(|x: c_int| ..)。用 Handle::new(closure) 创建、却按 Handle::<fn(i32)> 读取的句柄会触发 panic:this handle holds a closure, not `fn(i32) -> ()`: make it with `Handle::<fn(i32) -> ()>::new(..)` and read it with `Handle::<fn(i32) -> ()>::from_ptr(p)` 。
C 回调是 extern "C" fn,不捕获任何东西(refs-lang 5.9.10)。要从 C 调用闭包,把它保存在句柄中,并传入一个只有一行的 extern "C" fn,由它读回闭包并调用;不存在通用的跳板函数。直接把闭包传给 C 函数是错误,其帮助信息会提示这样做。
use bare::ffi::Handle;
use bare::ptr::CPtr;
extern "C" {
// void each(int n, void (*cb)(void *, int), void *user_data);
fn each(n: c_int, cb: extern "C" fn(CPtr<c_void>, c_int), ud: CPtr<c_void>);
}
extern "C" fn on_row(ud: CPtr<c_void>, i: c_int) {
let rows = unsafe { Handle::<List<str>>::from_ptr(ud) }.get();
rows.push(f"row {i}"); // the caller's list
}
extern "C" fn call(ud: CPtr<c_void>, i: c_int) {
let f = unsafe { Handle::<fn(c_int)>::from_ptr(ud) }.get();
f(i);
}
let rows: List<str> = [];
let h = Handle::new(rows);
unsafe { each(3, on_row, h.as_ptr()) };
h.release(); // rows.len() == 3
let total = Cell::new(0);
let f = Handle::<fn(c_int)>::new(|x: c_int| { total.set(total.get() + x); });
unsafe { each(5, call, f.as_ptr()) };
f.release(); // total.get() == 10
运行时一侧是 nabi_handle_new / nabi_handle_get / nabi_handle_retain / nabi_handle_release(refs-lang 8.5.12)。
#1.7.11. #[errno]:errno 与 GetLastError
#[errno]
extern "C" {
fn open(path: str, flags: c_int, ...) -> c_int;
}
extern "C" {
#[errno]
fn chdir(path: str) -> c_int;
}
// bare::ffi
fn errno() -> c_int; // errno as the last #[errno] call on this thread left it
fn set_errno(v: c_int); // the saved value and the C library's errno
fn last_error() -> u32; // Windows: GetLastError as that call left it; 0 elsewhere
fn set_last_error(v: u32); // the saved value and, on Windows, SetLastError
从 C 调用返回到下一行之间,线程可能运行运行时代码:离开原生状态时它可能要等待一次回收结束,还要解除 str 实参副本的固定。这些代码可能改变 errno。在 extern "C" 或 extern "system" 块上,或在其中的单个声明上写 #[errno],会让调用在返回后、其他任何代码运行之前,立即把 errno(在 Windows 上还有 GetLastError)保存到按线程区分的槽中。errno() 和 last_error() 读取保存的值,因此无论何时运行,得到的都是该次调用的值。
不写该属性时什么都不保存:errno() 返回该线程上最后一次 #[errno] 调用(或 set_errno)留下的值。set_errno 同时设置保存的值和 C 库的 errno,用于只通过 errno 报告错误的 C 函数(strtol:设为 0、调用、读取)。io::IoError::last_os_error()(2.23.0)根据保存的值创建 IoError:在 Windows 上,保存的 GetLastError 非零时用它,否则用保存的 errno。
use bare::ffi::{errno, set_errno};
let fd = unsafe { open("/no-such-dir/file", 0) }; //→ -1
let e = io::IoError::last_os_error(); // e.kind() == NotFound, e.os_code() == 2
set_errno(0);
在其他任何项上写 #[errno] 都是错误:在函数上为 `#[errno]` cannot be attached to a function; it goes on an extern block or an extern function;在 extern "nabi" 块上(运行时自己保存 errno)为 `#[errno]` and `#[leaf]` are for C declarations: put them on an `extern "C" { .. }` block or its functions。
#1.7.12. WideCStr / WideCString:wchar_t 字符串
Windows 的 W API 和 C 的 wchar_t 函数接受由 c_wchar 单元组成、以 NUL 结尾的字符串。这些类型保存这样的字符串:在 Windows 上为 UTF-16,在其他目标上每个字符一个单元(UTF-32)。API 在每个目标上都相同。
struct WideCString { .. } // private fields (0.5.10)
impl WideCString {
fn new(s: str) throws (NulError) -> WideCString; // s as units and a NUL; NulError::position() is a unit index
fn as_ptr(self) -> ConstPtr<c_wchar>;
fn as_wide_cstr(self) -> WideCStr;
fn as_units(self) -> Slice<c_wchar>; // without the NUL
fn to_str(self) -> str; // the string back; never fails
fn len(self) -> usize; // units before the NUL
}
struct WideCStr { .. }
impl WideCStr {
unsafe fn from_ptr(p: ConstPtr<c_wchar>) -> WideCStr | none; // copies up to the NUL; null → none
fn as_ptr(self) -> ConstPtr<c_wchar>;
fn as_units(self) -> Slice<c_wchar>; // without the NUL
fn as_units_with_nul(self) -> Slice<c_wchar>;
fn to_str(self) throws (Utf16Error) -> str;
fn to_str_lossy(self) -> str; // each bad unit → U+FFFD
fn len(self) -> usize;
}
两者都把单元和 NUL 保存在同一个 GC 对象中,并实现 Clone、PartialEq、Eq、Hash 和 Debug(WideCString("hi"))。as_ptr 的有效范围与 CStr::as_ptr 相同(1.7.2)。from_ptr 与 CStr::from_ptr 一样把 C 字符串复制进来:p 必须为 null,或指向一个存活的、以 NUL 结尾的 wchar_t 字符串。WideCString::new 在 str 中遇到 NUL 时抛出 NulError(1.7.2)。WideCStr::to_str 在 Windows 上遇到未配对的代理项时、在其他目标上遇到不是字符的单元时抛出 str::Utf16Error(2.15.6);valid_up_to() 是单元索引。
不带 NUL 和指针的 UTF-16 本身由 str::encode_utf16、str::from_utf16 和 str::from_utf16_lossy 处理(2.15.6)。由 C 填充的缓冲区是一个被固定的 List<u16>,用 str::from_utf16 读回:
// Windows
use bare::ffi::WideCString;
use bare::gc::pin;
use bare::ptr::{ConstPtr, Ptr};
extern "system" {
fn SetEnvironmentVariableW(name: ConstPtr<u16>, value: ConstPtr<u16>) -> i32;
fn GetEnvironmentVariableW(name: ConstPtr<u16>, buf: Ptr<u16>, size: u32) -> u32;
}
let name = try WideCString::new("NABI_WIDE_TEST");
let value = try WideCString::new("h\u{E9}\u{1F600}");
unsafe { SetEnvironmentVariableW(name.as_ptr(), value.as_ptr()) };
let buf: List<u16> = [];
for _ in 0..1024 { buf.push(0u16); }
let held = pin(buf);
let n = unsafe { GetEnvironmentVariableW(name.as_ptr(), held.as_data_ptr(), 1024u32) };
let back = try str::from_utf16(buf[0:n as usize]); //→ "hé😀"
#1.7.13. Library:加载共享库
struct Library { .. }
impl Library {
fn open(path: str) throws (LoadError) -> Library;
fn this() -> Library; // the program itself
fn raw_symbol(self, name: str) throws (SymbolError) -> CPtr<c_void>; // never null
unsafe fn symbol<F>(self, name: str) throws (SymbolError) -> F; // F: a C function pointer type
unsafe fn close(self) throws (LoadError);
}
struct LoadError { .. }
impl LoadError {
fn path(self) -> str; // the path given to open
fn message(self) -> str; // the system's reason
}
struct SymbolError { .. }
impl SymbolError {
fn name(self) -> str; // the symbol asked for
fn message(self) -> str; // the system's reason
}
open 在运行时加载共享库:在 Unix 上为 dlopen(path, RTLD_NOW | RTLD_LOCAL),在 Windows 上为 LoadLibraryW。只有名称时,在系统的库路径中搜索。this() 是程序本身:在 Unix 上包括它自己的符号和与它链接的每个库的符号,在 Windows 上只包括可执行文件导出的内容。raw_symbol 给出符号的地址。symbol::<F> 把函数作为 F 给出,F 必须是 C 函数指针类型(extern "C" fn(f64) -> f64、extern "system" fn() -> u32);其他类型会在地址转换为该类型之前触发 panic:`symbol::<i32>`: write the C function pointer type, `extern "C" fn(..) -> R`。它是 unsafe 的,因为 F 必须是该符号真实的签名。
库从不隐式卸载:Library 没有 Drop,close 是唯一的方式。close 是 unsafe 的,因为从库中取得的每个指针(符号、库返回的数据)在此之后都会悬垂;关闭 this() 不做任何事。Library 实现 Clone 和 Debug(Library("kernel32.dll")、Library(this))。
消息来自系统(dlerror、FormatMessageW)。LoadError 显示为 cannot load {path}: {message}(来自 close 时为 cannot close ..),SymbolError 显示为 cannot find symbol {name}: {message};路径或名称中含有 NUL 是错误,在询问系统之前就会报告(the path has a NUL byte at 1; remove it)。两者都实现 Display、Debug、Error、PartialEq、Eq 和 Clone。没有动态加载的目标(wasm32、无操作系统)也有这个类型,open 会以 this target has no dynamic loading 抛出错误。
use bare::ffi::Library;
fn main() throws (bare::ffi::LoadError | bare::ffi::SymbolError) {
let lib = try Library::open("libm.so.6");
let cos = try unsafe { lib.symbol::<extern "C" fn(f64) -> f64>("cos") };
println(f"{unsafe { cos(0.0) }}"); //→ 1
try unsafe { lib.close() };
}
发现错误? 在 GitHub 上编辑此页 最后更新: