# std::ffi

處理「Rust 以外的世界」使用的字串：作業系統的原生字串（`OsString`／`OsStr`）與 C 語言字串（`CString`／`CStr`）。

## 這個模組做什麼

FFI 是 Foreign Function Interface（外部函式介面）的縮寫，指 Rust 和其他語言、作業系統互相呼叫的介面。問題出在字串：Rust 的 `String` 保證是 UTF-8、長度另外記錄；但外面的世界規則不同。

| 型別 | 擁有／借用 | 代表 | 特性 |
| --- | --- | --- | --- |
| `OsString` | 擁有 | 作業系統原生字串 | 可能不是 UTF-8（Unix 檔名可以是任意位元組） |
| `OsStr` | 借用 | 同上 | `Path` 底層就是它 |
| `CString` | 擁有 | C 字串 | 結尾有 `\0`，中間不能有 `\0` |
| `CStr` | 借用 | 同上 | 常用來包裝 C 傳回的指標 |

和 `String`／`&str` 一樣，每組都是「擁有」與「借用」一對。日常最常在 [std::path](/pkg-path) 與 [std::env](/pkg-env) 碰到 `OsStr`；呼叫 C 函式庫時才需要 `CString`／`CStr`。

## 匯入

```rust
use std::ffi::{CStr, CString, OsStr, OsString, c_char};
```

`c_char`、`c_int` 等型別對應 C 的 `char`、`int`，在 Rust 1.64 起可以從 `std::ffi` 匯入。

## 常用 API

### OsString 與 OsStr：作業系統字串

`OsString` 可以從 `&str`、`String` 轉來，也能用 `push` 附加內容。轉回 Rust 字串時可能失敗，所以有三種方式：

| 方法 | 回傳 | 非 UTF-8 時 |
| --- | --- | --- |
| `to_str()` | `Option<&str>` | `None` |
| `to_string_lossy()` | `Cow<str>` | 不合法的部分換成 `�` |
| `into_string()` | `Result<String, OsString>` | `Err` 把原值還給你 |

簽名：

```rust
pub fn push<T: AsRef<OsStr>>(&mut self, s: T);
pub fn to_str(&self) -> Option<&str>;
pub fn to_string_lossy(&self) -> Cow<'_, str>;
pub fn into_string(self) -> Result<String, OsString>;
```

注意：`OsStr::len` 回傳的是內部編碼的位元組數，不是字元數；在 Windows 上內部編碼與 UTF-8 不同，不要拿它做跨平台計算。

範例：

```rust
use std::ffi::{OsStr, OsString};

fn main() {
    let mut name = OsString::from("report");
    name.push("-2024");
    name.push(".txt");
    println!("{:?} len={}", name, name.len());

    let borrowed: &OsStr = name.as_os_str();
    match borrowed.to_str() {
        Some(s) => println!("valid UTF-8: {}", s.to_uppercase()),
        None => println!("not UTF-8"),
    }
    println!("lossy: {}", borrowed.to_string_lossy());

    let back: Result<String, OsString> = name.into_string();
    println!("into_string ok: {}", back.is_ok());
}
```

輸出：

```text
"report-2024.txt" len=15
valid UTF-8: REPORT-2024.TXT
lossy: report-2024.txt
into_string ok: true
```

### 處理檔名的 OsStr：不轉成 String 也能判斷

`Path::file_name`、`extension` 回傳 `&OsStr`。很多判斷不必先轉成 `String`：`eq_ignore_ascii_case` 不分大小寫比較、`to_ascii_lowercase` 轉小寫、`as_encoded_bytes` 取得內部位元組來檢查開頭字元（Rust 1.74 起）。這樣即使檔名含非 UTF-8 位元組，程式也不會出錯。

簽名：

```rust
pub fn eq_ignore_ascii_case<S: AsRef<OsStr>>(&self, other: S) -> bool;
pub fn to_ascii_lowercase(&self) -> OsString;
pub fn as_encoded_bytes(&self) -> &[u8];
```

注意：`as_encoded_bytes` 的內容格式未指定，只適合和 ASCII 字元比對；要把位元組轉回 `OsStr` 必須用 `unsafe` 的 `from_encoded_bytes_unchecked`。

範例：

```rust
use std::ffi::OsStr;
use std::path::Path;

fn is_hidden(name: &OsStr) -> bool {
    name.as_encoded_bytes().first() == Some(&b'.')
}

fn main() {
    for p in ["/home/u/.profile", "/home/u/notes.md"] {
        let name: &OsStr = Path::new(p).file_name().unwrap();
        println!("{:?} hidden={}", name, is_hidden(name));
    }

    let ext = Path::new("song.MP3").extension().unwrap();
    println!("is mp3: {}", ext.eq_ignore_ascii_case("mp3"));
    println!("lowercase: {:?}", ext.to_ascii_lowercase());
}
```

輸出：

```text
".profile" hidden=true
"notes.md" hidden=false
is mp3: true
lowercase: "mp3"
```

### CString：建立給 C 用的字串

C 語言以 `\0` 標記字串結尾。`CString::new` 把 Rust 字串複製一份並在結尾加上 `\0`；如果內容中間已經有 `\0`，C 會在那裡提早截斷，所以 `new` 回傳 `NulError`，並告訴你位置。

`as_bytes` 不含結尾的 `\0`，`as_bytes_with_nul` 包含。

簽名：

```rust
pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError>;
pub fn as_bytes(&self) -> &[u8];
pub fn as_bytes_with_nul(&self) -> &[u8];
pub fn into_string(self) -> Result<String, IntoStringError>;
```

範例：

```rust
use std::ffi::CString;

fn main() {
    let owned = CString::new("hello").expect("no interior nul");
    println!("bytes: {:?}", owned.as_bytes());
    println!("with nul: {:?}", owned.as_bytes_with_nul());

    match CString::new("bad\0string") {
        Ok(_) => println!("ok"),
        Err(e) => println!("error at byte {}: {}", e.nul_position(), e),
    }

    let back: String = owned.into_string().unwrap();
    println!("back to String: {}", back);
}
```

輸出：

```text
bytes: [104, 101, 108, 108, 111]
with nul: [104, 101, 108, 108, 111, 0]
error at byte 3: nul byte found in provided data at position: 3
back to String: hello
```

### CStr：借用 C 字串

`CStr` 是借用版的 C 字串。建立方式：

- `c"..."` 字面值直接得到 `&'static CStr`（Rust 1.77 起）
- `CStr::from_bytes_with_nul`：位元組最後一個必須是 `\0`，且中間不能有 `\0`
- `CStr::from_bytes_until_nul`：讀到第一個 `\0` 為止，後面的忽略

`count_bytes` 回傳不含 `\0` 的長度（Rust 1.79 起），`to_str` 轉成 `&str`，`to_owned` 複製成 `CString`。

簽名：

```rust
pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError>;
pub fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError>;
pub fn to_str(&self) -> Result<&str, Utf8Error>;
pub fn count_bytes(&self) -> usize;
```

範例：

```rust
use std::ffi::CStr;

fn main() {
    let lit: &CStr = c"literal";
    println!("{:?} count_bytes={}", lit, lit.count_bytes());

    let raw: &[u8] = b"from bytes\0";
    let parsed = CStr::from_bytes_with_nul(raw).unwrap();
    println!("to_str: {:?}", parsed.to_str());

    let bad = CStr::from_bytes_with_nul(b"no terminator");
    println!("missing nul is error: {}", bad.is_err());

    let until = CStr::from_bytes_until_nul(b"stop\0ignored").unwrap();
    println!("until nul: {:?}", until);

    let owned = until.to_owned();
    println!("owned: {:?}", owned);
}
```

輸出：

```text
"literal" count_bytes=7
to_str: Ok("from bytes")
missing nul is error: true
until nul: "stop"
owned: "stop"
```

### 呼叫 C 函式：as_ptr 與 CStr::from_ptr

實際呼叫 C 時，用 `unsafe extern "C"` 區塊宣告函式（Rust 2024 edition 要求寫 `unsafe`），把 `CString::as_ptr()` 傳進去；C 回傳的 `*const c_char` 則用 `CStr::from_ptr` 包起來讀取。範例呼叫的 `strlen`、`strchr` 屬於 C 標準函式庫，標準庫已經連結它，不需要額外設定。

簽名：

```rust
pub fn as_ptr(&self) -> *const c_char;
pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr;
```

注意：`as_ptr` 回傳的指標只在 `CString` 存活期間有效。寫成 `CString::new(..).unwrap().as_ptr()` 會讓暫時值立刻被丟棄，留下懸置指標（dangling pointer），使用它是未定義行為。`from_ptr` 要求指標非空、指向以 `\0` 結尾的有效記憶體，且讀取期間內容不被修改，否則同樣是未定義行為。指標與 `unsafe` 的基礎見 [std::ptr](/pkg-ptr)。

範例：

```rust
use std::ffi::{CStr, CString, c_char};

unsafe extern "C" {
    fn strlen(s: *const c_char) -> usize;
    fn strchr(s: *const c_char, c: i32) -> *const c_char;
}

fn main() {
    let text = CString::new("key=value").unwrap();
    let len = unsafe { strlen(text.as_ptr()) };
    println!("strlen = {}", len);

    let found = unsafe { strchr(text.as_ptr(), b'=' as i32) };
    if !found.is_null() {
        let tail = unsafe { CStr::from_ptr(found) };
        println!("from '=': {:?}", tail.to_str().unwrap());
    }
}
```

輸出：

```text
strlen = 9
from '=': "=value"
```

### into_raw 與 from_raw：把所有權交給 C

當 C 函式庫要「保管」字串一段時間，用 `into_raw` 把 `CString` 轉成 `*mut c_char`，Rust 不再負責釋放；之後 C 把指標還回來時，用 `from_raw` 拿回所有權，離開作用域時才真正釋放記憶體。

簽名：

```rust
pub fn into_raw(self) -> *mut c_char;
pub unsafe fn from_raw(ptr: *mut c_char) -> CString;
```

注意：`from_raw` 只能接收先前由 `into_raw` 產生的指標，且每個指標只能還一次；拿 C 的 `malloc` 配置的字串來呼叫是未定義行為，因為兩邊的配置器不同。忘記呼叫 `from_raw` 則會造成記憶體洩漏。

範例：

```rust
use std::ffi::{CString, c_char};

fn give_to_c(s: &str) -> *mut c_char {
    CString::new(s).unwrap().into_raw()
}

fn take_back(p: *mut c_char) -> String {
    let owned = unsafe { CString::from_raw(p) };
    owned.into_string().unwrap()
}

fn main() {
    let ptr = give_to_c("ownership round trip");
    println!("pointer is null: {}", ptr.is_null());
    let s = take_back(ptr);
    println!("{}", s);
}
```

輸出：

```text
pointer is null: false
ownership round trip
```

## 重點整理

- `OsString`／`OsStr` 代表作業系統字串，可能不是 UTF-8；`Path` 就建在它上面
- 轉回 Rust 字串用 `to_str`（可能 `None`）或 `to_string_lossy`（不會失敗）
- `CString` 結尾自動加 `\0`，內容含 `\0` 時 `new` 回傳錯誤
- 保持 `CString` 存活到 C 用完指標為止，避免懸置指標
- `into_raw` 交出所有權，必須配對一次 `from_raw` 收回
