Reputation: 385
I have an array type of uint8_t in C. A function called getResultArray will return this array. How can I get this array in JavaScript?
uint8_t * getResultBuffer() { return resultBuffer }
Upvotes: 3
Views: 2001
Reputation: 5233
The pointer returned from the C function is an offset into the ArrayBuffer that Emscripten uses to represent memory. For viewing as uint8_t, access the memory using Module.HEAPU8
.
Here is an example, using em++:
fill_array.cpp:
#include "stdint.h"
extern "C" {
uint8_t* fill_array(int n);
}
uint8_t* fill_array(int n) {
uint8_t* arr = new uint8_t[n];
for(uint8_t i=0;i<n;++i)
arr[i] = i;
return arr;
}
index.html:
<!doctype html>
<html>
<body>
<script>
var Module = {
onRuntimeInitialized: function() {
var fill_array = Module.cwrap('fill_array', 'number', [])
var n = 16;
var ptr_from_wasm = fill_array(n);
var js_array = Module.HEAPU8.subarray(ptr_from_wasm, ptr_from_wasm + n);
alert(js_array);
},
};
</script>
<script async type="text/javascript" src="index.js"></script>
</body>
</html>
Results in the following:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
For this to work, you'll need to add the following arguments to em++:
-s EXPORTED_FUNCTIONS='["_fill_array"]' -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]'
See full source code in This repo
Upvotes: 4