简体   繁体   English

我可以从 Rust 代码调用 C 或 C++ 函数吗?

[英]Can I call C or C++ functions from Rust code?

Is it possible to call C or C++ functions within Rust?是否可以在 Rust 中调用 C 或 C++ 函数? If so, how is this done?如果是这样,这是如何完成的?

Rust doesn't support this directly, C++ function symbol mangling is implementation defined, so it will need a lot of support from Rust to handle this feature. Rust 不直接支持这一点,C++ 函数符号重整是实现定义的,因此它需要 Rust 的大量支持来处理这个特性。 It's not impossible but it's probably not going to happen.这并非不可能,但可能不会发生。

However, Rust claims to support the C language.然而,Rust 声称支持 C 语言。 This is clearly more easy to support, as it "only" needs to support the function calls of C. This is implementation-defined behavior too, but this doesn't change a lot and people agree to work together to share the same convention so you will not have a problem to use C as intermediary on common platform.这显然更容易支持,因为它“只”需要支持 C 的函数调用。这也是实现定义的行为,但这并没有太大变化,人们同意共同工作以共享相同的约定,因此在通用平台上使用 C 作为中介不会有问题。

So, to call C++ from Rust, you must pass by C.所以,要从 Rust 调用 C++,你必须通过 C。

To call C from Rust, the docs show this example :要从 Rust 调用 C, 文档显示了这个例子

extern "C" {
    fn abs(input: i32) -> i32;
}

fn main() {
    unsafe {
        println!("Absolute value of -3 according to C: {}", abs(-3));
    }
}

To call C++ from C, a C++ function must be defined like this :要从 C 调用 C++,必须像这样定义 C++ 函数:

// This C++ function can be called from C code
extern "C" void handler(int) {
    std::cout << "Callback invoked\n"; // It can use C++
}

To transmute this example to our example in Rust, that gives:将这个例子转换为我们在 Rust 中的例子,给出:

#include <cstdlib>
#include <cinttypes>

extern "C" std::int32_t abs(std::int32_t n) {
    return std::abs(static_cast<std::intmax_t>(n));
}

Rust can link to/call C functions via its FFI , but not C++ functions. Rust 可以通过其FFI链接到/调用 C 函数,但不能链接到/调用 C++ 函数。

While I don't know why you can't call C++ functions, it is probably because C++ functions are complicated .虽然我不知道为什么不能调用 C++ 函数,但可能是因为 C++ 函数很复杂

If you wish to call C functions from libc there is a rust crate that allows writing C like code directly in rust, some of it requires unsafe blocks.如果你想从libc调用 C 函数,有一个 rust crate 允许直接在 rust 中编写类似 C 的代码,其中一些需要不安全的块。

Below is an example of seting the nofile system limit.以下是设置 nofile 系统限制的示例。 Instructions for this code are in man 2 setrlimit , ie the code maps almost directly from C to rust.此代码的说明在man 2 setrlimit ,即代码几乎直接从 C 映射到 Rust。

use libc::rlimit;
use libc::setrlimit;
use libc::RLIMIT_NOFILE;

/// Set system limits on number of "open files"
pub fn increase_rlimit_nofile(limit: u64) -> i32 {
    let lim = rlimit {
        rlim_cur: limit,
        rlim_max: limit
    };
    unsafe {
        let rv: i32 = setrlimit(RLIMIT_NOFILE, &lim);
        return rv;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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