Passing array to c++ .wasm module. Emscripten

I have an array consisting of mask data for a corresponding image i need to pass to a c++ function compiled with emscripten. The mask array consists of values ranging from -1 to 255, so i guess an Int16Array must be used to represent the values. Is it possible to pass this array as a pointer to the wasm module? I know I have to allocate the memory and pass the pointer, but I am stuck on the following code. How do i correctly allocate and set the pointer in order for the c++ function to see the correct data?

The maskData is obtained as:

const mData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        var data = Array.prototype.slice.call(mData.data);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    let data = imageData.data;

    const dataLength = data.length;
    const maskDataLength = maskData.length;

    var dataPointer = Module._malloc(dataLength * data.BYTES_PER_ELEMENT);
    var maskDataPointer = Module._malloc(maskDataLength * 2);

    Module.HEAPU8.set(data, dataPointer);
    Module.HEAP16.set(maskData, maskDataPointer);

    let result = Module.ccall(
      "process",
      "number",
      ["number", "number", "number", "number", "number"],
      [dataPointer, dataLength, maskDataPointer, pos, neg]
    );

    data = new Int16Array(Module.HEAP16.buffer, result, dataLength);

    Module._free(dataPointer);
    Module._free(maskDataPointer);
    Module._free(result);

2 thoughts on “Passing array to c++ .wasm module. Emscripten”

Leave a Comment