代码之家  ›  专栏  ›  技术社区  ›  Justin Haug

从Rust编译到Emscripten的Javascript中获取数组

  •  4
  • Justin Haug  · 技术社区  · 7 年前

    我想生成一个字节向量( Vec<u8> Array Uint8Array 并将其发送到WebSocket或IndexedDB。

    How can I pass an array from JavaScript to Rust that has been compiled with Emscripten? ,这与我想做的正好相反,但非常相关。除此之外,我知道Emscripten中的数组类型,但不知道如何正确使用它。

    我对如何使其工作的最好猜测是尝试返回向量 as_mut_ptr ,并使用 Module.HEAPU8 .

    #[no_mangle]
    pub fn bytes() -> *mut u8 {
        vec![1, 2, 3].as_mut_ptr()
    }
    
    fn main() {}
    

    部分 指数html

    var Module = {
        wasmBinaryFile: "site.wasm",
        onRuntimeInitialized: main,
    };
    function main() {
        let ptr = Module._bytes();
        console.log(ptr);
        console.log(Module.HEAPU8.slice(ptr, ptr + 10));
        console.log(Module.HEAPU8.subarray(ptr, ptr + 100));
        let arr = Module.cwrap('bytes', 'array', []);
        console.log(arr());
    }
    

    5260296  site:11:13
    Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]  site:12:13
    Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90 more… ]  site:13:13
    5260296  site:15:13
    

    指向同一内存位置的两个指针可能是因为锈蚀会使 在其生命周期结束时写入 bytes )功能。

    对不起,如果我错过了Wasm和Emscripten的一些基础知识,我今天只构建了我的第一个Wasm hello world。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Shepmaster Tim Diekmann    7 年前

    一个人会回来 Vec<u8>

    有两种类似的解决方案:

    1. Box<Vec<u8>> 并定义另一个函数来提取

    2. 定义你自己的 Vec

    我用的是后者 here .

        2
  •  0
  •   Justin Haug    7 年前

    好的,在接受了@sebk的想法之后(非常感谢你的指点)。 This is what I came up with.

    它实际上工作得很好,所以我将快速描述它。我们需要一个表示,可以从JavaScript访问数组,因此主要需要一个指针和数组的长度(在 JsVec Box into_raw 所以我们可以返回一个原始指针到 并获取信息。为了防止锈菌掉落载体,我们需要忘记载体,使用 mem::forget

    在javascript世界中,它就像通过指针和 Module.HEAPU32 价值

    根据我的理解,它会自动删除 JsVec公司 足够了。

    编辑:

    this reddit comment's advice 并根据 JsBytes

    这在我的浏览器中很管用,要点也很管用。