Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emscripten pass array to C++ and change its values

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: enter image description here

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!

like image 900
Finn Eggers Avatar asked Nov 16 '25 04:11

Finn Eggers


1 Answers

Okay so I figured out the solution by trial and error. Module.ccall is supposed to take an array of arguments it reads.

 function getFloatArrayFromFunctionCall(func_name, size) {
     var res_ptr = Module._malloc(size * 4);
     Module.ccall(func_name, null, ["number"], [res_ptr]);
     var view = Module.HEAPF32.subarray(res_ptr >> 2, (res_ptr >> 2) + size);
     Module._free(res_ptr);
     return view;
 }

solves the problem. Hope this is helpfull for anyone stumbling across the same problem.

like image 160
Finn Eggers Avatar answered Nov 17 '25 20:11

Finn Eggers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!