我正在try 从CPP链接到Rust,然后从Rust程序链接回原始的CPP程序.
(这可能是XY的问题,所以我想做的是有一个用CPP加载模块写的游戏,用铁 rust 写的.所以我认为CPP将加载Ruust代码,然后注册物品等Ruust将调用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();
}
然后,我使用 crate 类型dylib
编译了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->;
希望这是足够的信息:)