I'm trying to compile my project in such a way that I can pass a javascript typed array into an exported wasm function.
From every tutorial I read online in order to do this I have to copy the buffer of the typed array into the wasm heap like this:
var buf = Module._malloc(desiredLength);
Module.HEAPU8.set(typedArray, buf);
Module.ccall('my_function', 'number', ['number'], [buf]);
However when I try to run this code in the browser I get this error:
Module._malloc is not a function
This is what I am using to compile my c++ code:
emcc myProject.cpp -s WASM=1 -s EXPORTED_FUNCTIONS="['_processData']" -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']" -O3 -o index.js
Is there any reason for this error? Did I set something up incorrectly? Any help would be much appreciated.
I encounter the same issue.
In my case, applying -O2 optimization instead of -O3 works fine.
It seems -O3 optimization may accidentally slice _malloc() from generated code.
However my other programs work correctly even with -O3.
I have no idea about the condition where this issue occurs.
Hmmm I wonder if compiling without --s ALLOW_MEMORY_GROWTH=1 is the problem.
I just tried my project again with this flag and it worked. I realize now that when you don't use the flag wasm automatically creates it's different heap arrays on wasm initialization to be a fixed length.
So there's no need to use malloc, just copy your array directly into HEAPU8 as the space has already been created for it. This seems to be working for me. Maybe it's just not clearly indicated in the tutorials that this is an available option?
The optimizer does more work in -O3, and it can remove malloc, as @h-matsuo said. To use malloc in a guaranteed way, you can export it by adding it to EXPORTED_FUNCTIONS. (Without that, the optimizer might succeed in removing it in some cases, but not others it depends on whether other things use malloc, like say some JS library code might end up keeping it alive.)
About memory growth - you do still need to call malloc to get a pointer to some free space you can use. Unless you have another way to get free space (like a function in compiled code could return some statically allocated memory).
What would be the proper syntax for exporting malloc as a function? I tried
-s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap', 'malloc', '_malloc']"
But it doesn't seem to work
It's a compiled function, so it goes on EXPORTED_FUNCTIONS. You can add it to your existing export with -s EXPORTED_FUNCTIONS="['_processData', '_malloc']".
Thank you that worked!
I noticed that if I call malloc from JavaScript, it never fails, even if the amount I want to allocate is larger than the memory I have on my machine! the question is there a way to verify whether or not there is enough memory to run my code?
Most helpful comment
It's a compiled function, so it goes on
EXPORTED_FUNCTIONS. You can add it to your existing export with-s EXPORTED_FUNCTIONS="['_processData', '_malloc']".