kovacsv kovacsv - 9 months ago 57
Javascript Question

How to use C++ allocated array in Emscripten generated code?

I have a C++ code like this:

extern "C" {

void MyCoolFunction (int** values)
int howManyValuesNeeded = 5;
*values = new int[howManyValuesNeeded];
for (int i = 0; i < howManyValuesNeeded; i++) {
(*values)[i] = i;


From C++ it can be used like this:

int *values = NULL;
MyCoolFunction (&values);
// do something with the values
delete[] values;

Of course the real code is much more complicated, but the point is that the function allocates an int array inside, and it decides what the array size will be.

I translated this code with Emscripten, but I don't know how could I access the array allocated inside the function from javascript. (I already know how to use exported functions and pointer parameters with Emscripten generated code, but I don't know how to solve this problem.)

Any ideas?


In Emscripten, memory is stored as a giant array of integers, and pointers are just indexes into that array. Thus, you can pass pointers back and forth between C++ and Javascript just like you do integers. (It sounds like you know how to pass values around, but if not, go here.)

Okay. Now if you create a pointer on the C++ side (as in your code above) and pass it over to Javascript, Emscripten comes with a handful of helper functions to allow you to access that memory. Specifically setValue and getValue.

Thus, if you passed your values variable into JS and you wanted to access index 5, you would be able to do so with something like:

var value5 = getValue(values+(5*4), 'i32');

Where you have to add the index times the number of bytes (5*4) to the pointer, and indicate the type (in this case 32 bit ints) of the array.