#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> 與可為 null
- 1.7.4. using 區塊:RAII
- 1.7.5. 安全包裝模式:分離 sys 與 safe
- 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> 與可為 null
權威定義見 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 與 safe
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);其他目標只使用編譯器內建的標頭檔(stddef.h、stdint.h、stdarg.h、stdbool.h、limits.h、float.h 等),除非在 -- 之後指定 --sysroot,而目標的標頭檔則在 -- 之後傳入(-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)。static 與 inline 函式會略過(沒有可連結的符號)。 - 函式指標變成
unsafe extern "C" fn(...) -> R | none(refs-lang 5.9.4;NULL =none)。 - 求值為整數、浮點數或字串常數的類物件巨集變成
const項目。 - 是 Nabi 關鍵字或基本型別名稱的 C 名稱會加上結尾的
_;函式與 static 以#[link_name]保留其 C 符號。 - 其他任何東西(128 位元整數、
__fp16、寬度超過 8 位元組的long double、向量與 block 型別、可變參數函式指標、執行緒區域變數、其他呼叫慣例)都會略過,並加上// 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")標籤、可為 null 性限定詞、__extension__、typeof、_Alignas、_Atomic、_Static_assert的宣告,匿名結構與聯集、位元欄位、彈性陣列成員、指定型別的列舉、block 指標(^)與向量型別。函式主體與初始化式會略過(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 |
| 可為 null 的 ptr | (預設) | Option<*const T> | ?*T | *C.struct_T(一律可為 null) | 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 函式接受以 NUL 結尾、由 c_wchar 單元組成的字串。這些型別存放這樣的字串:在 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 上編輯此頁 最後更新: