c++ - 如何将 C++ 程序链接到 Rust 程序,然后将该 Rust 程序链接回 C++ 程序? (cpp -> rust -> cpp)

标签 c++ rust g++ ld ffi

我正在尝试从 Cpp 链接到 Rust,然后从该 Rust 程序链接回原始 Cpp 程序。

(这可能是一个 xy 问题,所以我想做的是用 cpp 编写一个游戏,加载用 rust 编写的 mods。所以我认为 cpp 会加载 rust 代码,然后注册项目等 rust 会调用cpp游戏中的函数。)

但现在我只是使用快速测试环境:

Cpp 文件:

//main.cpp
#include "rust.h"
#include "main.h"
#include <stdio.h>

int main() {
        hello();
        print(100, 1.6, true);
        return 0;
}

void cpp() {
        printf("hello from cpp");
}

// main.h
void cpp();
// rust.h
// generated with cbindgen
#include <cstdarg>
#include <cstdint>
#include <cstdlib>
#include <ostream>
#include <new>

extern "C" {

void hello();

void print(int32_t a, float b, bool c);

} // extern "C"


Rust 文件:

// lib.rs
mod cpp;

#[no_mangle]
pub extern fn hello() {
    println!("hello from rust");
}

#[no_mangle]
pub extern fn print(a: i32, b: f32, c: bool) {
    println!("int: {}, float: {}, bool: {}", a, b, c);
    unsafe { cpp::cpp(); }
}
// cpp.rs
/* automatically generated by rust-bindgen 0.65.1 */

extern "C" {
    pub fn cpp();
}

然后我使用 dylib 的 crate 类型编译 Rust,因此它输出一个 .so 文件。 编译我使用的 cpp(rust 程序的名称是 external):

g++ -L ./external/target/debug/ -Wall main.cpp -l external

消息中存在哪些错误:

/usr/bin/ld: ./external/target/debug//libexternal.so: undefined reference to `cpp'
collect2: error: ld returned 1 exit status

如果我删除 rust 程序中对 cpp 的引用,那么流程就是 cpp -> rust ,一切都会编译得很好。只是当对 cpp 的引用位于 rust 中时,就会破坏 cpp -> rust -> cpp 流程。

希望这是足够的信息:)


最佳答案

像 Rust 一样,C++ 默认会损坏它的导出符号,为了避免这种情况,您必须声明 cpp() 来使用带有 extern "C" 的 C ABI:


extern "C" void cpp() {
    printf("hello from cpp");
}

以及 header main.h 中。

关于c++ - 如何将 C++ 程序链接到 Rust 程序,然后将该 Rust 程序链接回 C++ 程序? (cpp -> rust -> cpp),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76393598/

相关文章:

C++ 包括重新声明

c++ - 多线程作业队列管理器

c++ - 关于将输入存储到字符串中,并使用 cout 显示它

struct - 你能把 struct impl block 放在不同的文件中吗?

c++ - g++ 是否在函数模板重载方面表现不佳?

macos - VS Code 在 Mac 上不会在任何断点处停止

c++ - 合理支持的最低 GCC 版本是多少?

c++ - 我的文件依赖性有什么问题?

struct - 如何类型转换和继承 Rust 结构?

rust - Rust lang thread::sleep()在Windows上的游戏循环期间休眠几乎是指定时间的两倍