【问题标题】:How to call C function in Rust如何在 Rust 中调用 C 函数
【发布时间】:2019-08-05 06:42:43
【问题描述】:

我是一名 C 程序员,我正在尝试在我的应用程序中调用 Rust 函数,而 rust 函数还需要调用我的应用程序中存在的 C 函数。

我知道如果我想在 Rust 中调用 C 函数,我必须这样做

#[link(name = "mylib")]
extern "C" {
    pub fn c_function();
}

但是 c_function 不存在于任何库中,而仅存在于我的应用程序环境中。

例如: 我的 C 代码是

void c_function()
{
    return 1;
}

void main()
{
    rust_function();
}

我的 Rust 代码是(cargo new --lib myrustlib)

pub unsafe extern "C" fn  rust_function() {
    //If I want to call c_function which is in C world here, How could I do this?
    //I have tried using extern "C" {pub fn c_function();} but faild.  
    //And an error is outputted like this "undefined reference to `c_function'"
}

【问题讨论】:

  • 你想在编译时或运行时链接它,例如通过dlopen?
  • 我找到了一个可以帮助你的资源。 blog.jfo.click/calling-a-c-function-from-rust所以,请阅读并尝试解决。
  • rust book 中甚至有解释。 'm trying to call Rust function in my application and the rust function also need call C functions - 你想从 rust 中调用 C 代码还是从 C 中调用 rust 代码?
  • 要能够从 main exe 调用 lib 中的符号,您需要特殊标志,这是一件非常奇怪的事情。

标签: rust


【解决方案1】:

你在正确的轨道上。您可以使用 cbindgen 从 Rust 程序自动生成 C 标头,反之,使用 bindgen 的 Rust 绑定。​​

crate-type = ["lib", "staticlib", "cdylib"] 添加到Cargo.toml 以生成可以与C 程序链接的Rust 库的.a.so/.dylib/.dll 版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-21
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 2020-07-29
    相关资源
    最近更新 更多