I have a code instantiating a webassembly module containing c++ code creating an array. The _Z9createArrayi function returns me a pointer on an array it has created. I could read it easily by casting it with Int32Array(), but the problem is that I don't know how I can handle its size. In the case below, It gives me a gigantic array of the size of the memory buffer. In this case, the size is 12, so I could limit the size of the int32Array to 12. But I will have cases where I will not know the size of the created array, and I want to know how I can handle them at best.
javascript code:
async function main() {
// Read the wasm file.
let response = await fetch(wasmPath);
let res = await WebAssembly.instantiateStreaming(response, info);
const { memory, _Z9createArrayi} = res.instance.exports;
memoryManager.memory = memory;
const mult = 2;
let ptr = _Z9createArrayi(mult);
let result = new Int32Array(memory.buffer, ptr);
console.log(result);
}
c++ code:
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int *createArray(int multiplicator)
{
int *result = new int[12];
for (int i = 0; i < 12; ++i)
{
result[i] = i * multiplicator;
}
return result;
}