gpt4 book ai didi

c++ - 将调用 C++ 的 Rust 编译为 WASM

转载 作者:行者123 更新时间:2023-12-05 03:18:48 25 4
gpt4 key购买 nike

我找到了这个 How do I use a C library in a Rust library compiled to WebAssembly? ,但这依赖于 wasm-merge,已经是 discontinued .我的问题如下,我有一些 C++ 代码,我想从 Rust 调用这些代码,以便可以选择将生成的包编译为用于移动应用程序的 native 代码或用于 Node.js 的 Webassembly。目前,我有以下设置:

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
}

构建.rs

fn main() {
cc::Build::new()
.cpp(true)
.file("libTest.cpp")
.compile("libTest.a");
}

这在使用简单的 cargo build 编译为 native 代码时可以编译和工作,但不适用于构建 wasm,为此我正在做 cargo build --target wasm32-未知-未知。我得到了两个错误

  = 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?

最佳答案

(这不是真正的完整答案,但对于评论来说太长了。)

我可以编译你的例子

cc::Build::new()
.archiver("llvm-ar") // Takes care of "archive has no index" - emar might be an alternative
.cpp_link_stdlib(None) // Takes care of "unable to find library -lstdc++"
… // rest of your flags

但我不确定生成的二进制文件是否对您有用。特别是,它在 Debug模式下编译时包含 WASI 导入,如果您开始使用任何有趣的函数(例如 sin),您可能会遇到链接器错误。

理论上,您可以通过 .flag("--sysroot=/usr/share/wasi-sysroot/") 为 C++ 编译器提供一个完整的标准库(如果您有 wasi- sdk 或 wasi-libc++ 安装),但是

  • 我不确定如何最好地说明此文件夹通常安装位置的差异(可能类似于 this)
  • 我想你也必须在链接时传递这个标志,但我不知道如何(虽然它似乎没有工作)
  • 这将以 wasi 为目标,并且可能对您想到的任何基于 bindgen 的环境都没有用。

关于c++ - 将调用 C++ 的 Rust 编译为 WASM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73604042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com