Skip to content

Instantly share code, notes, and snippets.

@Sciss
Forked from aknuds1/library,js
Created December 27, 2020 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sciss/96652c5ff23d156afaa52c4de11c0262 to your computer and use it in GitHub Desktop.
Save Sciss/96652c5ff23d156afaa52c4de11c0262 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.
// "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)
#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