'Can EM_JS return complex values?
I'm writing some WebAssembly code using the emscripten macro EM_JS
. The javascript code inside the macro returns an array of bytes but by the time the C++ code gets it, it's just pointer so it doesn't know how many elements are actually in the array. So I need a way to return the array and its length.
EM_JS(const char*, RunJsFunction, (const char* inBytes), {
const outBytes = myMethod(inBytes);
return outBytes; // this turns into a raw pointer in C++
});
const char someBytes[3] = { 1, 2, 3};
const char* result = RunJsFunction(someBytes); // no idea how many bytes are in result
I came up with a hacky solution that involves the C++ code passing in an array of two elements that the javascript can use as a container to "return" some data to the C++ function. One element is used contain the pointer to the array that I want to return and the other contains its length. Kind of like return an object { arrayHead: 0x123abc, length: 5 }
but using an array instead. Anyway, it works but it's grody to the max.
EM_JS(void, CallWriteSerial, (const char* inBytes, const int* outArray), {
const res = myMethod(inBytes);
outArray[0] = res.pointer;
outArray[1] = res.length;
});
const char inBytes[5] = { 1, 2, 3, 4, 5 };
int output[2];
CallWriteSerial(inBytes, output);
// output is an array containing two elements, a pointer to the resulting byte array and its length
const char* outBytes = (const char*)output[0];
const int length = output[1];
Is there a better way to do this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|