簡體   English   中英

將調用 C++ 的 Rust 編譯為 WASM

[英]Compiling Rust that calls C++ to WASM

我發現了這個如何在編譯為 WebAssembly 的 Rust 庫中使用 C 庫? ,但這依賴於wasm-merge,它已經停產了。 My problem is the following, I have some C++ code that I would like to call from Rust in order to have the option to compile the resulting package either to native code for use in mobile apps or to Webassembly for use in Node.js. 目前,我有以下設置:

libTest.cpp

extern "C"{
    int test_function(int i){
        return i;
    }
}

庫文件

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編譯為本機代碼時編譯並工作,但不適用於構建為 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++

這是 go 的正確方法嗎?如果是,我該如何解決上述錯誤? 如果沒有,我如何最好的 go 關於從 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

但我不確定生成的二進制文件是否對您有用。 特別是,它在調試模式下編譯時包含 WASI 導入,如果您開始使用任何有趣的函數(例如sin ),您可能會收到 linker 錯誤。

理論上,您可以通過.flag("--sysroot=/usr/share/wasi-sysroot/")為 C++ 編譯器提供完整的標准庫(如果您安裝了 wasi-sdk 或 wasi-libc++),但是

  • 我不確定如何最好地解決此文件夾通常安裝位置的差異
  • 我認為您還必須在鏈接時傳遞此標志,但我不知道如何(盡管它似乎可以正常工作)
  • 這將針對 wasi,並且可能對您想到的任何基於 bindgen 的環境都沒有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM