用 Rust 编写 .cdylib(.so) 文件
新建一个 lib 项目
cargo new --lib hello
修改 Cargo.toml 内 lib 的 crate-type
[lib]
crate-type = ["cdylib"]
添加 .cargo/config.toml
# The Darwin linker doesn't allow undefined symbol by default
# Building cdylib as plugin, failure on mac with missing host symbols, works on linux
# https://users.rust-lang.org/t/building-cdylib-as-plugin-failure-on-mac-with-missing-host-symbols-works-on-linux/28297
[target.'cfg(target_os = "macos")']
rustflags = ["-C", "link-args=-Wl,-undefined,dynamic_lookup"]
可以开始在 lib.rs 写 C 接口了
// 让 C 来调用我们的函数
#[no_mangle]
unsafe extern "C" fn hello_world(p: *mut std::ffi::c_void) -> *mut std::ffi::c_void {
p
}
我们调用 C 的函数,要先声明一下
extern "C" {
use std::ffi::c_int;
use std::ffi::c_uint;
use std::ffi::c_void;
pub fn foo(a: c_uint, b: c_int) -> c_int;
pub fn bar(a: *mut c_void, b: c_int) -> c_int;
pub fn set_callback(cb: unsafe extern "C" fn(ud: *mut c_void) -> c_int);
}
github 仓库
+V why_null 请备注:from博客园