Rust 调用C/C++
Rust 调用C/C++
需要引入cc依赖
Cargo.toml
[package]
name = "rust-call-c"
version = "0.1.0"
authors = ["ice <bsqql123@163.com>"]
build = "build.rs"
[dependencies]
libc = "0.2"
[build-dependencies]
cc = "1.0"
build.rs
extern crate cc;
fn main() {
cc::Build::new()
.file("src/double.c")
.compile("libdouble.a");
}
main.rs
extern crate libc;
extern {
fn double_input(input: libc::c_int) -> libc::c_int;
}
//TODO
fn main() {
let input = 4;
let output = unsafe { double_input(input) };
println!("{} * 2 = {}", input, output);
}
double.c
int double_input(int input) {
return input * 2;
}
具体例子在
https://github.com/iceqing/rust-call-c
这里是一个比较完整的例子,有各种语言的示例代码
https://github.com/iceqing/rust-ffi-examples