[英]How to call a Rust function in C?
發布此消息時向我顯示的第一個“類似問題”稱為“如何在 Rust 中調用 C function”。 這與我需要的相反。 Every tutorial I can find that technically does answer my question, only does so by exporting the Rust function in a DLL so a C executable can call it, using extern "C"
.
But I have a Rust executable that is calling a C DLL function that takes a Rust function pointer as a parameter (I haven't actually written this C function yet). 任何基本示例演示如何執行此操作? I've already got Rust calling some of the C DLL functions, but I need to write code for both Rust and C so that C can execute a Rust callback.
If you have this C code compiled to a library named lib.dll
, exporting a single function which accepts a pointer to a function which takes no arguments and returns nothing:
__declspec(dllexport) void foo(void (*callback)()) {
callback();
}
然后這個 Rust 代碼會將 function callback
發送到 C ZC1C425268E48385F14ZA70。 執行后,它會打印"callback()"
行:
extern "C" fn callback() -> () {
println!("callback()");
}
fn main() {
println!("main()");
call_dynamic();
}
fn call_dynamic() -> Result<u32, Box<dyn std::error::Error>> {
unsafe {
let lib = libloading::Library::new("lib.dll")?;
let foo: libloading::Symbol<extern "C" fn(extern "C" fn()) -> u32> = lib.get(b"foo")?;
Ok(foo(callback))
}
}
您應該在控制台中看到:
main()
callback()
我在 Windows 上,並使用以下命令編譯了 C 代碼:
gcc --shared lib.c -o lib.dll
Rust 代碼運行如下:
cargo run
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.