【问题标题】:Pass some array parameters into wasm将一些数组参数传递给 wasm
【发布时间】:2021-06-12 00:47:39
【问题描述】:

我想调用wasm的init函数,它的C代码如下,所以我需要将数组从javascript传递给wasm。

int  EMSCRIPTEN_KEEPALIVE init(int* playRecipes1, int* playChefs1, int* recipe2Change1,int* scoreCacheNoEquipIndex1, int* scoreAddCacheNoEquip1,short* disordePermuation1) {
playRecipes = playRecipes1;
playChefs = playChefs1;

recipe2ChangeLength = recipe2Change1[0];
scoreAddCacheNoEquipLength = scoreAddCacheNoEquip1[1];
scoreCacheNoEquipIndexLength = scoreCacheNoEquipIndex1[1];


recipe2Change = (int*)(recipe2Change1+1);
scoreCacheNoEquipIndex = (int * )(scoreCacheNoEquipIndex1 + 2);
scoreAddCacheNoEquip = (int *)(scoreAddCacheNoEquip1 + 2);
disordePermuation = (short *)(disordePermuation1+2);

return recipe2ChangeLength;

}

了解到传递数组,可以使用Module._malloc()来创建数组。但是_malloc的返回值很大, 所以,当我使用 Module.HEAPU8.set (data, dataPointer) 时,我遇到了错误: Uncaught (in promise) RangeError: offset is out of bounds。 在 Int32Array.set()

每次运行程序,第一次调用Module._malloc(),返回值总是5245672。

如:

function arrayToIntMemorySegment( arrays) {
let length1 = arrays.length;
let length2 = arrays[0].length;
let size = (length1 * length2 + 2);

let ptr = Module._malloc(size * 4);
let segment = new Int32Array(size);
let index = 0;

segment[index++]=length1;
segment[index++]=length2;

for (let i = 0; i < length1; i++) {
    for (let i2 = 0; i2 < length2; i2++) {
        segment[index++]=arrays[i][i2];
    }
}

Module.HEAP32.set(segment, ptr);
return ptr;

}

【问题讨论】:

    标签: javascript c++ memory webassembly emscripten


    【解决方案1】:

    HEAP32 是您的内存的 32 位视图,但 malloc 返回字节偏移量,因此您需要将 ptr &gt;&gt; 2 作为第二个参数传递给 Module.HEAP32.set。

    如果您改用 HEAP8 或 HEAPU8,则可以直接使用 ptr。

    【讨论】:

    • 从 malloc (5245672) 返回的值看起来差不多,因为 emscripten 默认为堆栈保留 5Mb。
    • 谢谢,你是对的。请你再帮帮我好吗?如果我想了解为什么需要(ptr >> 2),我应该从哪里学习?
    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多