用 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 仓库

https://github.com/hangj/demo-c-rust-call-each-other

posted on 2024-09-27 17:10  明天有风吹  阅读(31)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园