繁体   English   中英

你如何从 JS 读取在 wasm 中设置的数组?

[英]How do you read an array that was set in wasm from JS?

我有一个简单的setArray.cpp文件,如下所示:

int* x = new int[3];

extern "C" int* setArray() {
  
  x[0] = 11;
  x[1] = 22;
  x[2] = 33;
  return x;

}

我编译它并导出函数如下:

em++ -O1 setArray.cpp -o setArray.js -s EXPORTED_FUNCTIONS='["_setArray"]'

在我的 JS 代码中,我尝试调用setArray()期望取回数组x的地址,然后读取它的内容,但是当我读取内存时,我只得到零。

以下是test-setArray.js的内容:

const fs = require('fs');

const memory = new WebAssembly.Memory({
    initial: 1,
    maximum: 1
});
const heap = new Uint8Array(memory.buffer);

const imports = {
    env: {
        memory: memory,
        DYNAMICTOP_PTR: 4096,
        abort: function(err) {
            throw new Error('abort ' + err);
        },
        __cxa_throw: function(ptr, type, destructor) {
            console.error('cxa_throw: throwing an exception, ' + [ptr,type,destructor]);
        },
        __cxa_allocate_exception: function(size) {
            console.error('cxa_allocate_exception' + size);
            return false; // always fail
        },
        _emscripten_get_heap_size: function() {
            return heap.length;
        },
        emscripten_resize_heap: function(size) {
            return false; // always fail
        },
        emscripten_memcpy_big: function(dest, src, count) {
            heap.set(heap.subarray(src, src + count), dest);
        }
    }
};

const wasmSource = new Uint8Array(fs.readFileSync("setArray.wasm"));
const wasmModule = new WebAssembly.Module(wasmSource);
const wasmInstance = new WebAssembly.Instance(wasmModule, imports);

function setArray() {
    const loc = wasmInstance.exports.setArray();
    console.log(loc, heap[loc], heap[loc+1], heap[loc+2]);
}

setArray();

console.log语句输出:

0 0 0 0

我希望看到 11、22、33 被打印出来。 感觉就像我错过了一些明显的东西。 知道它可能是什么吗?

好的,我找到了答案:我缺少 3 个 Emscripten 标志:

  • -Wl,--import-memory告诉主机环境(JS)导入内存(而不是默认导出)
  • -s TOTAL_MEMORY=6MB设置将使用的初始内存
  • [可选] -s ALLOW_MEMORY_GROWTH=1允许在运行时从 JS 增长内存

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM