這個問題在這里已經有了答案: 為什么我在 Rust 中的 C strlen() 也會在 print 中計算字串切片!`s`變數之后的宏? (1 個回答) 昨天關門。
我在玩 Rust FFI,我試圖將printf具有可變引數的 C 函式與我的 Rust 可執行檔案鏈接起來。運行可執行檔案后,我目睹了一些奇怪的行為。
這是我的銹代碼:
use cty::{c_char, c_int};
extern "C" {
fn printf(format: *const c_char, ...) -> c_int;
}
fn main() {
unsafe {
printf("One number: %d\n".as_ptr() as *const i8, 69);
printf("Two numbers: %d %d\n".as_ptr() as *const i8, 11, 12);
printf(
"Three numbers: %d %d %d\n".as_ptr() as *const i8,
30,
31,
32,
);
}
}
這是運行后的輸出cargo run:
cargo run
Compiling c-bindings v0.1.0 (/home/costin/Rust/c-bindings)
Finished dev [unoptimized debuginfo] target(s) in 0.20s
Running `target/debug/c-bindings`
One number: 1
Two numbers: 1 11376
Three numbers: 0 0 0
Two numbers: 11 12
Three numbers: 0 0 56
Three numbers: 30 31 32
我看起來像第一個printf用隨機引數呼叫第二個和第三個,然后第二個用隨機引數printf呼叫第三個,因為預期的輸出應該是:
One number: 1
Two numbers: 11 12
Three numbers: 30 31 32
誰能向我解釋為什么會發生這種奇怪的行為?
uj5u.com熱心網友回復:
Rust 字串不像printf預期的那樣以 null 結尾。您需要\0在格式字串的末尾手動包含或使用CString:
printf("One number: %d\n\0".as_ptr() as *const i8, 69);
use std::ffi::CString;
let s = CString::new("One number: %d\n").unwrap();
printf(s.as_ptr(), 69);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424907.html
上一篇:如何為值范圍執行此函式?
