简体   繁体   English

使用javascript的const * const * input调用C webassembly函数

[英]Calling C webassembly function with const *const *inputs from javascript

I am planning to use an existing c library in the web using webassembly. 我打算使用webassembly在网络上使用现有的c库。

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 对于传递数组的第三个参数*options ,我通常使用Module._malloc()并在如下所示在该内存指针位置中设置了所有必需的值之后发送内存指针,并且工作正常

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. 但是我将如何发送像double const *const *inputs (second)和double *const *outputs (last)参数这样的参数。 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. 我使用emscripten创建wasm和javascript包装器(如果有帮助)。

inputsValues should be a Uint32Array, not a Float64Array; inputsValues应该是Uint32Array,而不是Float64Array; pointers are 32-bit unsigned integers in emscripten. 指针是emscripten中的32位无符号整数。

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. 我注意到您为指针的inputs数组分配了64个字节,该空间可容纳16个指针,但只能设置一个。 (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.) (如果每次迭代有16个项目,那很好,只要您的实际代码设置其他项目即可。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM