我正在尝试做一个非常简单的测试,以了解如何从C/C++调用Rust函数。
我的C++代码:
#include <iostream>
#include <cstdint>
extern "C" {
int32_t add_one(int32_t x);
} // extern "C"
using namespace std;
int main() {
int32_t x = 14;
cout << x << endl;
cout << add_one(x) << endl;
cout << x << endl;
}
我的Rust代码:#[no_mangle]
pub extern "C" fn add_one(x: i32) -> i32 {
x + 1
}
编译到库中后,给出了.dll
和.d
文件,可针对以下内容进行编译:g++ main.c libc_rust.a -o output.exe
如我所料,这给了我14 15 14
。如何使我的Rust函数不返回整数,而是将
x
用作引用,并将x
的值增加1,从而提供14 15 15
输出?如果我使用括号写
pub extern "C" fn add_one(x: i32) -> ()
,则意味着返回值是单位。我不知道确切的“单位”是什么,但在这种情况下似乎可以完成void
的工作。
最佳答案
#[no_mangle]
// See note below
pub extern "C" fn add_one(x: &mut i32) {
*x += 1;
}
#include <iostream>
#include <cstdint>
extern "C" {
void add_one(int32_t *x);
} // extern "C"
using namespace std;
int main() {
int32_t x = 14;
cout << x << endl;
add_one(&x);
cout << x << endl;
cout << x << endl;
}
通过在function参数中使用&mut
,我们要求调用者提供有效的引用。除其他外,这要求:确保这些条件取决于函数的调用者,否则将导致未定义的行为。
也可以看看:
关于c++ - 从C++调用Rust时,如何通过引用传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63709218/