gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:20:06 27 4
gpt4 key购买 nike

是否可以在 Rust 中调用 C 或 C++ 函数?如果是这样,这是如何完成的?

最佳答案

Rust 不直接支持此功能,C++ 函数符号重整是实现定义的,因此需要 Rust 的大量支持才能处理此功能。这并非不可能,但可能不会发生。

不过,Rust声称支持C语言。这显然更容易支持,因为它“只”需要支持 C 的函数调用。这也是实现定义的行为,但这并没有太大改变,人们同意共同努力以共享相同的约定,所以在通用平台上使用 C 作为中介不会有问题。

因此,要从 Rust 调用 C++,您必须通过 C。

从 Rust 调用 C,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++,必须像 this 一样定义 C++ 函数:

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

将这个例子转化为我们在 Rust 中的例子,给出:

#include <cstdlib>
#include <cinttypes>

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

关于c++ - 我可以从 Rust 代码调用 C 或 C++ 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24105186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com