如何静态链接通过FFI彼此依赖的Rust和C源?
问题描述:
什么是最小的Makefile或cargo
/rustc
+ cc
调用静态链接彼此依赖的Rust和C源?像这样(改编自alexcrichton/rust-ffi-examples),这是类似于example in the Rust docs:如何静态链接通过FFI彼此依赖的Rust和C源?
的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库吗?
答
这与'c-to-rust' example没有什么不同。
这是我不理解编译和链接阶段之间的区别;在链接时间之前Rust文件对GLOBAL_CONSTANT
的依赖性不会被解析,所以创建librust.a
时没有问题,然后再将其与可执行文件链接起来。
你的问题不是很清楚。你有什么*已经尝试*?有[整个站点](http://jakegoulding.com/rust-ffiomnibus/)致力于通过工作示例从其他语言(包括C)调用Rust代码。说“C库”这样的东西会增加混淆,因为你的问题中没有C库*;据推测称为“主”的文件将被编译成可执行文件(可能首先通过一个对象)。 – Shepmaster