c - 如何通过 FFI 静态链接相互依赖的 Rust 和 C 源代码?

标签 c rust static-linking ffi

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

主程序

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 库吗?

最佳答案

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

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

关于c - 如何通过 FFI 静态链接相互依赖的 Rust 和 C 源代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40435371/

相关文章:

c++ - OpenMP 4 对齐选项?

c - 处理 void 函数输入检查的最佳实践

rust - 代码无需借用即可工作,但我无法通过借用使其工作

ios - 链接同一库的两个版本(相同的符号)

c++ - 项目无法与 libcurl 静态库链接

c++ - 为什么不鼓励静态链接 glibc?

objective-c - 未初始化的外部 NSString 用法

c - C中不同输出内容的文件复制

unit-testing - 编写 Substrate Runtime Test 时快进时间

rust - 如何将 (String, String) 元组上的迭代器转换为 (&str, &str) 的迭代器?