我可以从Rust代码调用C或C ++函数吗? [英] Can I call C or C++ functions from Rust code?
问题描述
是否可以在Rust中调用C或C ++函数?如果是这样,怎么办?
Is it possible to call C or C++ functions within Rust? If so, how is this done?
推荐答案
Rust不直接支持此功能,因此C ++函数符号修饰是实现定义的,因此它将需要Rust的大量支持才能处理此功能。这不是不可能,但可能不会发生。
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. It's not impossible but it's probably not going to happen.
但是,Rust声称支持C语言。这显然更容易支持,因为它仅需要支持C的函数调用。这也是实现定义的行为,但这并没有太大变化,人们同意一起共享相同的约定,因此
However, Rust claims to support the C language. 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.
因此,要从Rust调用C ++,必须通过C。
So, to call C++ from Rust, you must pass by C.
要从Rust调用C,请文档显示了此示例:
To call C from Rust, the docs show this example:
extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
unsafe {
println!("Absolute value of -3 according to C: {}", abs(-3));
}
}
要从C调用C ++,必须使用C ++函数定义为此:
To call C++ from C, a C++ function must be defined like this:
// This C++ function can be called from C code
extern "C" void handler(int) {
std::cout << "Callback invoked\n"; // It can use C++
}
将此示例转换为Rust中的示例,给出:
To transmute this example to our example in Rust, that gives:
#include <cstdlib>
#include <cinttypes>
extern "C" std::int32_t abs(std::int32_t n) {
return std::abs(static_cast<std::intmax_t>(n));
}
这篇关于我可以从Rust代码调用C或C ++函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!