从 C++ 调用 Rust 时如何通过引用传递参数?

moh*_*tux 0 c++ rust

我正在尝试进行一个非常简单的测试,以了解如何从 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;
}
Run Code Online (Sandbox Code Playgroud)

我的锈代码:

#[no_mangle]
pub extern "C" fn add_one(x: i32) -> i32 {
    x + 1
}
Run Code Online (Sandbox Code Playgroud)

编译到一个库,这给出了一个.dll和一个.d文件来编译:

g++ main.c libc_rust.a -o output.exe
Run Code Online (Sandbox Code Playgroud)

正如我所料,这给了我14 15 14.

如何让我的 Rust 函数不返回整数,而是x作为参考并将 的值增加x1,给出输出14 15 15

如果我pub extern "C" fn add_one(x: i32) -> ()用括号写,那意味着返回值是单位。我不知道“单位”到底是什么,但void在这种情况下似乎可以完成这项工作。

She*_*ter 5

#[no_mangle]
// See note below
pub extern "C" fn add_one(x: &mut i32) {
    *x += 1;
}
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)

通过&mut在函数参数中使用,我们要求调用者提供有效的引用。除其他外,这要求:

  • 它不是NULL
  • 正确对齐
  • 它不为任何其他值设置别名。

由函数的调用者来确保这些条件,否则会导致未定义的行为。

也可以看看: