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);
--
You received this message because you are subscribed to the Google Groups
"emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/emscripten-discuss/ce90e07f-da17-42ac-bb2f-af40147b0341n%40googlegroups.com.