我发现了这篇文章 How do I use a C library in a Rust library compiled to WebAssembly?,但它依赖于已经停止更新的 wasm-merge(详情请参考 此链接)。我的问题是:我有一些 C++ 代码,我想从 Rust 中调用这些代码,以便可以编译出结果包,用于移动应用程序中的本地代码,或者编译为 WebAssembly,用于在 Node.js 中使用。目前,我的设置如下:
libTest.cpp
extern "C"{
int test_function(int i){
return i;
}
}
lib.rs
use wasm_bindgen::prelude::*;
#[link(name = "Test")]
extern "C"{
pub fn test_function(i: i32) -> i32 ;
}
#[wasm_bindgen]
pub fn test_function_js(i : i32) -> i32{
let res = unsafe{test_function(i)};
res
}
build.rs
fn main() {
cc::Build::new()
.cpp(true)
.file("libTest.cpp")
.compile("libTest.a");
}
使用简单的cargo build
编译成本机代码可以编译并工作,但用于wasm构建时不起作用,我正在使用cargo build --target wasm32-unknown-unknown
进行构建。在那里我遇到了两个错误。
= note: rust-lld: error: /[path to my project]/target/wasm32-unknown-unknown/debug/build/rustCpp-cc5e129d4ee03598/out/libTest.a: archive has no index; run ranlib to add one
rust-lld: error: unable to find library -lstdc++
这样做是正确的吗?如果是,我该如何解决上述错误?如果不是,我该如何最好地从Rust调用C++并将其编译为wasm?