It's my first time working with webassembly and I got to the following problem. A solution, which I dont know how to apply, exists in the official docs of emscripten. I also scanned through the web to find a working solution but none has worked for me so far.
Basically I need to get some array out of my C++ code after it has executed. For this purpose, I made a new function within my C++ code which copies the relevant data to some array which has been allocated within emscripten.
The C++ code looks like this:
void copy_to_array(std::vector<float> &vec, float* res){
std::memcpy(res, vec.begin().base(), sizeof(float) * vec.size());
for(int i = 0; i < vec.size(); i++){
std::cout << "copying array entry: " << i << " : " << vec[i] << " -> " << res[i] << std::endl;
}
}
EMSCRIPTEN_KEEPALIVE void wasm_get_displacement_x(float* res){
copy_to_array(wasm_result_displacement_x, res);
}
I made a function to copy the result from the internal vector wasm_result_displacement_x
to the given float array res
.
I know that the values of the array are not 0 since the std::cout
call shows the following:
My code within javascript looks like this:
function getFloatArrayFromFunctionCall(func_name, size) {
var res_ptr = Module._malloc(size * 4);
Module.ccall(func_name, null, ["number"], res_ptr);
let mem_view = Module.HEAPF32.subarray(res_ptr, res_ptr + size);
console.log(mem_view);
Module._free(res_ptr);
}
getFloatArrayFromFunctionCall("wasm_get_displacement_x", n_nodes)
It seems like I made a mistake when trying to read the content of the module memory.
Using the getValue
approach based on this answer doesnt work either.
I am very happy for any help or advice!