用 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博客园
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律