我正在玩 Rust FFI,我试图将printf具有可变参数的 C 函数与我的 Rust 可执行文件链接起来。运行可执行文件后,我目睹了一些奇怪的行为。
这是我的 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,
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是运行后的输出cargo run:
cargo run
Compiling c-bindings v0.1.0 (/home/costin/Rust/c-bindings)
Finished dev [unoptimized + debuginfo] target(s) in 0.20s …Run Code Online (Sandbox Code Playgroud)