FFI:呼叫 C
最後更新
FFI(Foreign Function Interface,外部函式介面)讓 Rust 呼叫 C 函式庫,也讓 C 程式呼叫 Rust 寫的函式。
extern "C" 與 ABI
函式在機器碼層級怎麼傳參數、怎麼回傳,稱為 ABI(Application Binary Interface)。Rust 自己的 ABI 沒有固定,C 的 ABI 則是各語言共通的「通用語」。
extern "C" 就是宣告「這個函式用 C 的方式呼叫」。C 的型別在 Rust 用 std::ffi 裡的別名表示:
| C | Rust |
|---|---|
int | c_int |
char | c_char |
const char * | *const c_char |
void * | *mut c_void |
size_t | usize |
double | f64(或 c_double) |
unsafe extern "C" 區塊:宣告 C 函式
在
unsafe extern "C" { ... } 裡寫出 C 函式的簽名,就能從 Rust 呼叫。macOS 與 Linux 的 Rust 程式預設就會連結 C 標準函式庫(libc),所以 abs、strlen 不需要額外設定。c"hello" 是 C 字串字面值(C-string literal),型別是 &CStr,結尾自動補上 \0(Rust 1.77 起,見 Rust 1.77)。注意:編譯器無法檢查你寫的簽名和 C 端是否一致,寫錯參數型別就是未定義行為,所以呼叫這些函式一律要
unsafe。觀念見 unsafe Rust。範例:
- use std::ffi::{c_char, c_int};
- unsafe extern "C" {
- fn abs(x: c_int) -> c_int;
- fn strlen(s: *const c_char) -> usize;
- }
- fn main() {
- let n = unsafe { abs(-42) };
- let len = unsafe { strlen(c"hello".as_ptr()) };
- println!("abs(-42) = {n}");
- println!("strlen = {len}");
- }
輸出:
- abs(-42) = 42
- strlen = 5
unsafe extern 區塊在 Rust 1.82 起可用(見 Rust 1.82);Rust 2024 edition 規定 extern 區塊一定要加 unsafe。這段無法編譯:- use std::ffi::c_int;
- extern "C" {
- fn abs(x: c_int) -> c_int;
- }
- fn main() {
- println!("{}", unsafe { abs(-1) });
- }
- error: extern blocks must be unsafe
- --> main.rs:3:1
- |
- 3 | extern "C" {
- | ^
- | |
- | _help: needs `unsafe` before the extern keyword: `unsafe`
- | |
- 4 | | fn abs(x: c_int) -> c_int;
- 5 | | }
- | |_^
safe fn:標記可以安全呼叫的外部函式
unsafe extern 的意思是「我保證這裡的宣告正確」。對於任何參數都不會出事的函式(例如 abs、toupper 只收整數),可以在宣告前加 safe,之後呼叫就不用 unsafe。沒有標記的函式(或標 unsafe fn)仍需要 unsafe。這個語法和 unsafe extern 一起在 Rust 1.82 起可用。範例:
- use std::ffi::{c_char, c_int};
- unsafe extern "C" {
- safe fn abs(x: c_int) -> c_int;
- safe fn toupper(c: c_int) -> c_int;
- fn strlen(s: *const c_char) -> usize;
- }
- fn shout(text: &str) -> String {
- text.bytes()
- .map(|b| toupper(b as c_int) as u8 as char)
- .collect()
- }
- fn main() {
- println!("{}", abs(-7));
- println!("{}", shout("hello ffi"));
- println!("{}", unsafe { strlen(c"abc".as_ptr()) });
- }
輸出:
- 7
- HELLO FFI
- 3
字串與記憶體
CString 傳給 C,CStr 接回來
C 字串以
\0 結尾、中間不能有 \0;Rust 的 String 則另外記錄長度。兩邊交換字串的方式:| 方向 | 做法 |
|---|---|
| Rust → C | CString::new(s)? 建立,.as_ptr() 傳出 |
| C → Rust | CStr::from_ptr(p) 包裝,再 .to_str() 轉成 &str |
下例中
strdup 由 C 端配置記憶體複製字串,回傳的指標必須交還給 C 的 free 釋放,不能交給 Rust 的 drop。原則是「誰配置、誰釋放」。注意:
strlen 回傳位元組數,不是字元數;CString::new 遇到字串中間有 \0 會回傳 Err。.as_ptr() 取得的指標只在 CString 還活著時有效,寫成 CString::new("x").unwrap().as_ptr() 會在這行結束時就釋放,留下懸空指標。範例:
- use std::ffi::{CStr, CString, c_char, c_void};
- unsafe extern "C" {
- fn strlen(s: *const c_char) -> usize;
- fn strdup(s: *const c_char) -> *mut c_char;
- fn free(p: *mut c_void);
- }
- fn main() {
- let owned = CString::new("台北 101").unwrap();
- println!("位元組數:{}", unsafe { strlen(owned.as_ptr()) });
- let copy = unsafe { strdup(owned.as_ptr()) };
- if copy.is_null() {
- return;
- }
- let text = unsafe { CStr::from_ptr(copy) }.to_str().unwrap().to_owned();
- unsafe { free(copy.cast()) };
- println!("C 複製回來:{text}");
- match CString::new("a\0b") {
- Ok(_) => println!("ok"),
- Err(e) => println!("錯誤:{e}"),
- }
- }
輸出:
- 位元組數:10
- C 複製回來:台北 101
- 錯誤:nul byte found in provided data at position: 1
可變參數與緩衝區
C 的可變參數函式(如
printf 家族)在宣告時用 ... 表示。下例用 snprintf 把格式化結果寫進 Rust 準備的緩衝區,buf.len() 告訴 C 最多能寫多少,避免溢位。注意:可變參數沒有型別檢查,
%d 對應的參數必須真的是 c_int,所以範例寫 42 as c_int;型別不符是未定義行為。範例:
- use std::ffi::{CStr, c_char, c_int};
- unsafe extern "C" {
- fn snprintf(buf: *mut c_char, size: usize, format: *const c_char, ...) -> c_int;
- }
- fn main() {
- let mut buf = [0 as c_char; 32];
- let written = unsafe {
- snprintf(buf.as_mut_ptr(), buf.len(), c"%s=%05d".as_ptr(), c"id".as_ptr(), 42 as c_int)
- };
- let text = unsafe { CStr::from_ptr(buf.as_ptr()) };
- println!("{written} {:?}", text);
- }
輸出:
- 8 "id=00042"
把 Rust 函式交給 C 回呼
用
extern "C" fn 定義的 Rust 函式可以當函式指標傳給 C。C 標準函式庫的 qsort 需要一個比較函式,回傳負數、0、正數表示大小關係;Ordering as c_int 剛好是 -1、0、1。注意:從
extern "C" fn 往外 panic 會讓程式直接中止(abort,Rust 1.81 起),回呼函式內應避免 panic。範例:
- use std::ffi::{c_int, c_void};
- unsafe extern "C" {
- fn qsort(
- base: *mut c_void,
- count: usize,
- size: usize,
- compare: extern "C" fn(*const c_void, *const c_void) -> c_int,
- );
- }
- extern "C" fn by_value(a: *const c_void, b: *const c_void) -> c_int {
- let (a, b) = unsafe { (*a.cast::<i32>(), *b.cast::<i32>()) };
- a.cmp(&b) as c_int
- }
- fn main() {
- let mut numbers = [42, -3, 17, 0, 8];
- unsafe {
- qsort(
- numbers.as_mut_ptr().cast(),
- numbers.len(),
- size_of::<i32>(),
- by_value,
- );
- }
- println!("{numbers:?}");
- }
輸出:
- [-3, 0, 8, 17, 42]
從 C 呼叫 Rust
#[unsafe(no_mangle)] 與 #[repr(C)]
要讓 C 呼叫 Rust 函式,需要兩件事:
| 寫法 | 作用 |
|---|---|
pub extern "C" fn | 用 C 的 ABI 編譯這個函式 |
#[unsafe(no_mangle)] | 保留原本的函式名稱,不做名稱修飾(name mangling),C 端才找得到 |
#[repr(C)] | 結構體欄位依 C 的規則排列,兩邊記憶體配置才一致 |
no_mangle 是不安全屬性(unsafe attribute):兩個 crate 匯出同名符號會讓連結結果出錯,所以 Rust 1.82 起可以寫成 #[unsafe(no_mangle)],Rust 2024 edition 則必須這樣寫。這段在 2024 edition 無法編譯:- #[no_mangle]
- pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
- a + b
- }
- error: unsafe attribute used without unsafe
- --> main.rs:1:3
- |
- 1 | #[no_mangle]
- | ^^^^^^^^^ usage of unsafe attribute
- |
- help: wrap the attribute in `unsafe(...)`
- |
- 1 | #[unsafe(no_mangle)]
- | +++++++ +
完整範例:Rust 端編成靜態函式庫(staticlib),C 端用 clang 編譯並連結。目錄內有兩個檔案:
lib.rs:- use std::ffi::{CStr, c_char};
- #[repr(C)]
- pub struct Point {
- pub x: f64,
- pub y: f64,
- }
- #[unsafe(no_mangle)]
- pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
- a + b
- }
- #[unsafe(no_mangle)]
- pub extern "C" fn rust_distance(p: Point) -> f64 {
- (p.x * p.x + p.y * p.y).sqrt()
- }
- #[unsafe(no_mangle)]
- pub unsafe extern "C" fn rust_char_count(s: *const c_char) -> usize {
- if s.is_null() {
- return 0;
- }
- let text = unsafe { CStr::from_ptr(s) };
- text.to_str().map(|t| t.chars().count()).unwrap_or(0)
- }
main.c:- #include <stdio.h>
- #include <stdint.h>
- #include <stddef.h>
- typedef struct {
- double x;
- double y;
- } Point;
- int32_t rust_add(int32_t a, int32_t b);
- double rust_distance(Point p);
- size_t rust_char_count(const char *s);
- int main(void) {
- Point p = {3.0, 4.0};
- printf("rust_add(2, 40) = %d\n", rust_add(2, 40));
- printf("rust_distance = %.1f\n", rust_distance(p));
- printf("rust_char_count = %zu\n", rust_char_count("台灣 Rust"));
- printf("rust_char_count(NULL) = %zu\n", rust_char_count(NULL));
- return 0;
- }
指令(macOS/Linux):
- rustc --edition 2024 --crate-type staticlib -O -o libffidemo.a lib.rs
- clang main.c -L. -lffidemo -o main
- ./main
輸出:
- rust_add(2, 40) = 42
- rust_distance = 5.0
- rust_char_count = 7
- rust_char_count(NULL) = 0
rust_char_count 收的是原始指標,Rust 無法保證它有效,所以宣告成 unsafe extern "C" fn,並先檢查空指標。Linux 上連結時可能需要加 -lpthread -ldl -lm,依平台而異。實際專案常用 Cargo 的 crate-type = ["staticlib"] 或 ["cdylib"],見 Cargo。重點整理
unsafe extern "C" { ... }宣告 C 函式,Rust 2024 必須加unsafe;不會出事的函式可標safe fn- C 型別用
std::ffi的c_int、c_char、c_void;簽名寫錯編譯器抓不到,是未定義行為 - 字串:
CString傳出、CStr::from_ptr接回,c"..."字面值直接得到&CStr - 記憶體「誰配置、誰釋放」:C 配置的用
free,Rust 配置的交回 Rust 釋放 - 給 C 呼叫的函式寫
#[unsafe(no_mangle)] pub extern "C" fn,共用結構體加#[repr(C)] - 從
extern "C" fn往外 panic 會中止程式