Last active
August 17, 2021 02:31
-
-
Save aknuds1/533f7b228aa46e9ee4c8 to your computer and use it in GitHub Desktop.
Emscripten - how to pass an array of floating point numbers from JavaScript to a C callback, to let the latter fill it with data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "use strict"; | |
var LibraryTst = { | |
initialize: function (callback) { | |
callback = Runtime.getFuncWrapper(callback, 'vi') | |
var numBytes = 2 * Float32Array.BYTES_PER_ELEMENT | |
var ptr = Module._malloc(numBytes) | |
try { | |
callback(ptr) | |
console.log('Callback filled buffer like so:') | |
var i = 0 | |
for (i = 0; i < 2; ++i) { | |
console.log(HEAPF32[(ptr/Float32Array.BYTES_PER_ELEMENT)+i]) | |
} | |
} | |
finally { | |
Module._free(ptr) | |
} | |
}, | |
} | |
mergeInto(LibraryManager.library, LibraryTst) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
extern "C" { | |
void initialize(void (*callback)(float*)); | |
} | |
void callback(float* output) | |
{ | |
for (int i = 0; i < 2; ++i) | |
{ | |
output[i] = i+1; | |
} | |
printf("Callback was invoked\n"); | |
} | |
int main() | |
{ | |
initialize(&callback); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment