gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:01:22 25 4
gpt4 key购买 nike

什么是最小的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com