0
votes

I am planning to use an existing c library in the web using webassembly.

Below is the gist of the function of the library that I do not have any control over the program

#include <stdio.h>
#include <stdlib.h>

int avg(int size, double const *const *inputs, double const *options, double *const *outputs) {
    const double *input = inputs[0];
    const int period = (int)options[0];
    double *output = outputs[0];
    const double scale = 1.0 / period;
    double sum = 0;

    int i;
    for (i = 0; i < period; ++i) {
        sum += input[i];
    }

    *output++ = sum * scale;

    for (i = period; i < size; ++i) {
        sum += input[i];
        sum -= input[i-period];
        *output++ = sum * scale;
    }

    return 0;
}

For the third argument *options passing an array I usually Module._malloc() and send the memory pointer after setting all the required values in that memory pointer location like below and it works fine

var optionsPointer = Module._malloc(options_required.length * 64);
var optionsValues = new Float64Array(Module.wasmMemory.buffer, optionsPointer, options_required.length);
optionsValues.set(option_values);

But how would I send parameters like double const *const *inputs(second) and double *const *outputs (last) arguments. I tried creating pointer array of pointer like below for the second argument with no success.

var inputMemoryPointer = Module._malloc(size * 64);
var inputMemoryValues = new Float64Array(Module.wasmMemory.buffer, inputMemoryPointer, size);
inputMemoryValues.set(user_inputs[input]);

var inputsPointer = Module._malloc(64)
var inputsValues = new Float64Array(Module.wasmMemory.buffer, inputsPointer, 1);
inputsValues.set([inputMemoryPointer]);

I use emscripten to create wasm and the javascript wrapper if it helps.

1

1 Answers

1
votes

inputsValues should be a Uint32Array, not a Float64Array; pointers are 32-bit unsigned integers in emscripten.

Also double-check the sizes of your allocations; I notice you're allocating 64 bytes for the inputs array of pointers which is room for 16 pointers, but only setting one. (If there are meant to be 16 items for each iteration, then that's fine as long as your real code sets the other items.)