我已经找到了这个How do I use a C library in a Rust library compiled to WebAssembly?,但这依赖于wasm-merge,它一直是discontinued.我的问题是,我有一些C++代码,我想从Rust调用它们,以便能够 Select 将生成的包编译为本地代码,以便在移动应用程序中使用,或者编译为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呢?