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

标签 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;
}
我的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,我们要求调用者提供有效的引用。除其他外,这要求:
  • 不能为空
  • 正确对齐
  • 它没有别名任何其他值。

  • 确保这些条件取决于函数的调用者,否则将导致未定义的行为。
    也可以看看:
  • The Rust FFI Omnibus
  • Passing a Rust variable to a C function that expects to be able to modify it
  • How do I pass a reference to mutable data in Rust?
  • What's the difference between placing "mut" before a variable name and after the ":"?
  • 关于c++ - 从C++调用Rust时,如何通过引用传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63709218/

    相关文章:

    c++ - 让冒泡排序在 C++ 中工作

    C++ Builder 字符数组寻址

    c++ - 来自 C++ 代码的 Shell 命令

    rust - 如何读取bevy中的鼠标运动?

    rust - 有没有办法在新线程上启动 tokio::Delay 以允许主循环继续?

    c++ - 为什么这些字符串不会在 C++ 中连接?

    c++ - 如何修改 QSet 的元素?

    rust - 这个 for 循环模式有没有名字,如果有,有没有更好的写法?

    rust - 将枚举变体用作函数的这种奇怪语法是什么?

    http - 如何在 Rust 中使用媒体文件正确格式化 HTTP 响应