【问题标题】:How do you statically link Rust and C sources that depend on each other through FFI?你如何通过 FFI 静态链接相互依赖的 Rust 和 C 源?
【发布时间】:2017-03-19 00:53:20
【问题描述】:

什么是最小的 Makefile 或 cargo/rustc + cc 调用以静态链接相互依赖的 Rust 和 C 源?类似这样的东西(改编自alexcrichton/rust-ffi-examples),类似于example in the Rust docs

main.c

struct contrived { double x; double y; }

double GLOBAL_CONSTANT = 100;

extern double consume_input(struct contrived input);

int main() {
    double output = consume_input({.x = 1, .y = 2});
    printf("Got %f.", output);
    return 0;
}

lib.rs

#![crate_type = "staticlib"]

#[repr(C)]
#[derive(Clone, Copy)]
struct Contrived {
    x: f64,
    y: f64,
}

extern {
    #[link(name = "main", kind = "static")]
    static GLOBAL_CONSTANT: f64;
}


#[no_mangle]
pub extern fn consume_input(input: Contrived) -> f64 {
    input.x - input.y + GLOBAL_CONSTANT
}

如果 lib.rs 只依赖于结构体,它实际上不依赖于 C 库吗?

【问题讨论】:

  • 你的问题不是很清楚。您已经尝试过什么?有 entire sites 专门用于从其他语言(包括 C)调用 Rust 代码并提供工作示例。说“C 库”之类的话会增加混乱,因为您的问题中没有 没有 C 库;大概名为“main”的文件将被编译成可执行文件(可能首先通过对象)。

标签: c rust static-linking ffi


【解决方案1】:

这与'c-to-rust' example 没有什么不同。

这是我不理解编译和链接阶段之间的区别; Rust 文件对 GLOBAL_CONSTANT 的依赖直到链接时间才解决,因此创建 librust.a 然后稍后将其与可执行文件链接是没有问题的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多