繁体   English   中英

如何在 C 中调用 Rust function?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM