将一些数组参数传递到wasm中



我想调用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;

}

我学会了传递数组,我可以使用模块_malloc((创建数组。但是_ malloc的返回值非常大因此,当我使用Module.HEAPU8.set(data,dataPointer(时,我会遇到错误:Uncaught(在promise中(RangeError:offset越界。在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;

}

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

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

相关内容

  • 没有找到相关文章

最新更新