Pass arrays between javascript and C++

190 views
Skip to first unread message

dland

unread,
Mar 15, 2022, 11:21:42 PM3/15/22
to emscripten-discuss
Emscripten's embind features work really well for passing basic objects back and forth between javascript and C++ but arrays seem trickier.

Some use cases I'd be interested in are
  • Arrays of basic data types like int
  • Objects containing an array member field
  • Arrays of objects
Most of what I can find about this on the interwebs seems to use the technique of allocating the arrays on the wasm heap, then passing around pointers as unsigned int along with the array size, as with the example below (apparently embind won't support passing pointers so you have to use to unsigned int). While this does seem to work, it seems like kind of a lot just to pass an array around. It also makes memory management tricky. And I'm not sure how you would support passing an array of objects back and forth.

Dealing with lists of things is such a basic concept it seems like there would be a better way (not to throw shade on all the greatly appreciated hard work that has gone into getting things this far). Am I just missing something?


Sample code:

C++:
struct ArrayData
{
unsigned int ptr;
unsigned int len;
};

ArrayData GetArray()
{
int* array = (int*)malloc(sizeof(int) * 3);
array[0] = 1;
array[1] = 22;
array[2] = 333;

ArrayData data;
data.ptr = (unsigned int)array;
data.len = 3;
return data;
}

Javascript:
const data = Module.GetArray();
const start = data.ptr / Int32Array.BYTES_PER_ELEMENT;
const end = start + data.len;
const array = Module.HEAP32.subarray(start, end);
console.log(array);
Module._free(data.ptr);




Reply all
Reply to author
Forward
0 new messages