Pass array to C function using emscripten

I think this question is similar to this , and I used most of the answer to my problem, but I still have problems:

First 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 pass a pointer to an array of my C function and populate it with some information. I am compiling this code with

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

My html / js code is as follows:

 <!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's garbage. Is the malloc buffer too small?

+2
source share
1 answer

Module.getValue accepts an optional second argument, indicating the type by which the "pointer" should be dereferenced as by default, it is 'i8' , which means that 32-bit signed integers are dereferenced as 8-bit integers without receiving garbage, but wrap the bugs.

The fix is ​​simple, you just need to indicate 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 fillArray to

 #include <stdint.h> void fillArray(int32_t* a, int32_t len) 

The revelant section of emscripten docs can be found here

+2
source

Source: https://habr.com/ru/post/1014464/


All Articles