Pass array to C function with emscripten

不打扰是莪最后的温柔 提交于 2019-12-11 00:25:11

问题


I think this question is similar to this one and I used most of it's answer for my problem, but I still have issues:

First the C code:

#include <stdio.h>

extern "C"
{
    void fillArray(int* a, int len)
    {
        for (int i = 0; i<len; i++)
        {
            a[i] = i*i;
        }

        for (int j = 0; j < len; ++j)
        {
            printf("a[%d] = %d\n", j, a[j]);
        }
    }
}

I'm passing a pointer to an array to my C function and fill it with some information. I compile this code with

emcc -o writebmp.js dummyCode\cwrapCall.cxx -s EXPORTED_FUNCTIONS="['_fillArray']"

My html/js code is the following:

<!doctype html>
<html>
  <script src="writebmp.js"></script>
  <script>
    fillArray = Module.cwrap('fillArray', null, ['number', 'number']);
    var nByte = 4
    var length = 20;
    var buffer = Module._malloc(length*nByte);
    fillArray(buffer, length);
    for (var i = 0; i < length; i++)
    {
        console.log(Module.getValue(buffer+i*nByte));
    }
  </script>
</html>

When I run the script the output I get is correct until the 12th element, after that it is garbage. Is the buffer I malloc too small?


回答1:


Module.getValue takes an optional second argument, denoting the type that the 'pointer' should be dereferenced as and by default this is 'i8', meaning the 32 bit signed integers are being dereferenced as 8 bit integers and so you're not getting garbage, but wrap around errors.

Fixing this is simple, you just need to specify that the 'pointer' passed to Module.getValue should be dereferenced as a 32 bit signed integer:

console.log(Module.getValue(buffer+i*nByte, 'i32'));

It might be safer and clearer to change the declaration of fillArray to

#include <stdint.h>

void fillArray(int32_t* a, int32_t len)

The revelant section of the emscripten docs can be found here



来源:https://stackoverflow.com/questions/40083041/pass-array-to-c-function-with-emscripten

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!