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 裡的別名表示:
CRust
intc_int
charc_char
const char **const c_char
void **mut c_void
size_tusize
doublef64(或 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。
範例:
  1. use std::ffi::{c_char, c_int};
  2. unsafe extern "C" {
  3. fn abs(x: c_int) -> c_int;
  4. fn strlen(s: *const c_char) -> usize;
  5. }
  6. fn main() {
  7. let n = unsafe { abs(-42) };
  8. let len = unsafe { strlen(c"hello".as_ptr()) };
  9. println!("abs(-42) = {n}");
  10. println!("strlen = {len}");
  11. }

輸出:
  1. abs(-42) = 42
  2. strlen = 5

unsafe extern 區塊在 Rust 1.82 起可用(見 Rust 1.82);Rust 2024 edition 規定 extern 區塊一定要加 unsafe。這段無法編譯:
  1. use std::ffi::c_int;
  2. extern "C" {
  3. fn abs(x: c_int) -> c_int;
  4. }
  5. fn main() {
  6. println!("{}", unsafe { abs(-1) });
  7. }

  1. error: extern blocks must be unsafe
  2. --> main.rs:3:1
  3. |
  4. 3 | extern "C" {
  5. | ^
  6. | |
  7. | _help: needs `unsafe` before the extern keyword: `unsafe`
  8. | |
  9. 4 | | fn abs(x: c_int) -> c_int;
  10. 5 | | }
  11. | |_^

safe fn:標記可以安全呼叫的外部函式


unsafe extern 的意思是「我保證這裡的宣告正確」。對於任何參數都不會出事的函式(例如 abs、toupper 只收整數),可以在宣告前加 safe,之後呼叫就不用 unsafe。沒有標記的函式(或標 unsafe fn)仍需要 unsafe。這個語法和 unsafe extern 一起在 Rust 1.82 起可用。
範例:
  1. use std::ffi::{c_char, c_int};
  2. unsafe extern "C" {
  3. safe fn abs(x: c_int) -> c_int;
  4. safe fn toupper(c: c_int) -> c_int;
  5. fn strlen(s: *const c_char) -> usize;
  6. }
  7. fn shout(text: &str) -> String {
  8. text.bytes()
  9. .map(|b| toupper(b as c_int) as u8 as char)
  10. .collect()
  11. }
  12. fn main() {
  13. println!("{}", abs(-7));
  14. println!("{}", shout("hello ffi"));
  15. println!("{}", unsafe { strlen(c"abc".as_ptr()) });
  16. }

輸出:
  1. 7
  2. HELLO FFI
  3. 3

字串與記憶體


CString 傳給 C,CStr 接回來


C 字串以 \0 結尾、中間不能有 \0;Rust 的 String 則另外記錄長度。兩邊交換字串的方式:
方向做法
Rust → CCString::new(s)? 建立,.as_ptr() 傳出
C → RustCStr::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() 會在這行結束時就釋放,留下懸空指標。
範例:
  1. use std::ffi::{CStr, CString, c_char, c_void};
  2. unsafe extern "C" {
  3. fn strlen(s: *const c_char) -> usize;
  4. fn strdup(s: *const c_char) -> *mut c_char;
  5. fn free(p: *mut c_void);
  6. }
  7. fn main() {
  8. let owned = CString::new("台北 101").unwrap();
  9. println!("位元組數:{}", unsafe { strlen(owned.as_ptr()) });
  10. let copy = unsafe { strdup(owned.as_ptr()) };
  11. if copy.is_null() {
  12. return;
  13. }
  14. let text = unsafe { CStr::from_ptr(copy) }.to_str().unwrap().to_owned();
  15. unsafe { free(copy.cast()) };
  16. println!("C 複製回來:{text}");
  17. match CString::new("a\0b") {
  18. Ok(_) => println!("ok"),
  19. Err(e) => println!("錯誤:{e}"),
  20. }
  21. }

輸出:
  1. 位元組數:10
  2. C 複製回來:台北 101
  3. 錯誤:nul byte found in provided data at position: 1

可變參數與緩衝區


C 的可變參數函式(如 printf 家族)在宣告時用 ... 表示。下例用 snprintf 把格式化結果寫進 Rust 準備的緩衝區,buf.len() 告訴 C 最多能寫多少,避免溢位。
注意:可變參數沒有型別檢查,%d 對應的參數必須真的是 c_int,所以範例寫 42 as c_int;型別不符是未定義行為。
範例:
  1. use std::ffi::{CStr, c_char, c_int};
  2. unsafe extern "C" {
  3. fn snprintf(buf: *mut c_char, size: usize, format: *const c_char, ...) -> c_int;
  4. }
  5. fn main() {
  6. let mut buf = [0 as c_char; 32];
  7. let written = unsafe {
  8. snprintf(buf.as_mut_ptr(), buf.len(), c"%s=%05d".as_ptr(), c"id".as_ptr(), 42 as c_int)
  9. };
  10. let text = unsafe { CStr::from_ptr(buf.as_ptr()) };
  11. println!("{written} {:?}", text);
  12. }

輸出:
  1. 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。
範例:
  1. use std::ffi::{c_int, c_void};
  2. unsafe extern "C" {
  3. fn qsort(
  4. base: *mut c_void,
  5. count: usize,
  6. size: usize,
  7. compare: extern "C" fn(*const c_void, *const c_void) -> c_int,
  8. );
  9. }
  10. extern "C" fn by_value(a: *const c_void, b: *const c_void) -> c_int {
  11. let (a, b) = unsafe { (*a.cast::<i32>(), *b.cast::<i32>()) };
  12. a.cmp(&b) as c_int
  13. }
  14. fn main() {
  15. let mut numbers = [42, -3, 17, 0, 8];
  16. unsafe {
  17. qsort(
  18. numbers.as_mut_ptr().cast(),
  19. numbers.len(),
  20. size_of::<i32>(),
  21. by_value,
  22. );
  23. }
  24. println!("{numbers:?}");
  25. }

輸出:
  1. [-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 無法編譯:
  1. #[no_mangle]
  2. pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
  3. a + b
  4. }

  1. error: unsafe attribute used without unsafe
  2. --> main.rs:1:3
  3. |
  4. 1 | #[no_mangle]
  5. | ^^^^^^^^^ usage of unsafe attribute
  6. |
  7. help: wrap the attribute in `unsafe(...)`
  8. |
  9. 1 | #[unsafe(no_mangle)]
  10. | +++++++ +

完整範例:Rust 端編成靜態函式庫(staticlib),C 端用 clang 編譯並連結。目錄內有兩個檔案:
lib.rs:
  1. use std::ffi::{CStr, c_char};
  2. #[repr(C)]
  3. pub struct Point {
  4. pub x: f64,
  5. pub y: f64,
  6. }
  7. #[unsafe(no_mangle)]
  8. pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
  9. a + b
  10. }
  11. #[unsafe(no_mangle)]
  12. pub extern "C" fn rust_distance(p: Point) -> f64 {
  13. (p.x * p.x + p.y * p.y).sqrt()
  14. }
  15. #[unsafe(no_mangle)]
  16. pub unsafe extern "C" fn rust_char_count(s: *const c_char) -> usize {
  17. if s.is_null() {
  18. return 0;
  19. }
  20. let text = unsafe { CStr::from_ptr(s) };
  21. text.to_str().map(|t| t.chars().count()).unwrap_or(0)
  22. }

main.c:
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <stddef.h>
  4. typedef struct {
  5. double x;
  6. double y;
  7. } Point;
  8. int32_t rust_add(int32_t a, int32_t b);
  9. double rust_distance(Point p);
  10. size_t rust_char_count(const char *s);
  11. int main(void) {
  12. Point p = {3.0, 4.0};
  13. printf("rust_add(2, 40) = %d\n", rust_add(2, 40));
  14. printf("rust_distance = %.1f\n", rust_distance(p));
  15. printf("rust_char_count = %zu\n", rust_char_count("台灣 Rust"));
  16. printf("rust_char_count(NULL) = %zu\n", rust_char_count(NULL));
  17. return 0;
  18. }

指令(macOS/Linux):
  1. rustc --edition 2024 --crate-type staticlib -O -o libffidemo.a lib.rs
  2. clang main.c -L. -lffidemo -o main
  3. ./main

輸出:
  1. rust_add(2, 40) = 42
  2. rust_distance = 5.0
  3. rust_char_count = 7
  4. 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 會中止程式

資料來源