小编Cos*_*Sin的帖子

为什么在 Rust 中使用可变参数链接和调用 C 函数会导致随机函数被调用?

我正在玩 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)

function ffi variadic-functions rust rust-cargo

1
推荐指数
1
解决办法
531
查看次数

标签 统计

ffi ×1

function ×1

rust ×1

rust-cargo ×1

variadic-functions ×1