Pass a JavaScript array as argument to a WebAssembly function

后端 未结 2 1446
一整个雨季
一整个雨季 2020-12-13 10:49

I would like to test WebAssembly for doing some complex array calculations.

So I\'ve written a simple C++ function adding two int arrays containing 3 e

2条回答
  •  借酒劲吻你
    2020-12-13 11:15

    So thanks to other similar questions :

    Pass array to C function with emscripten

    How to handle passing/returning array pointers to emscripten compiled code?

    And API docs :

    https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#getValue

    I have figured it out. To examplify how to pass an array to wasm function / get an array back, I have implemented a simple array copy in C++ :

    #include 
    
    extern "C" {
    
    int* copy_array(int* in_array, int length) {
      int out_array[length];
      for (int i=0; i

    Which you can compile like this :

    emcc wasm_dsp.cpp -s WASM=1 -s "MODULARIZE=1" -s "EXPORT_NAME='WasmDsp'" -s "BINARYEN_METHOD='native-wasm'" -s "EXPORTED_FUNCTIONS=['_copy_array']" -o build/wasm_dsp.js

    And run in the browser like this :

    
    
      
        
        
        
        
      
      
    
      
    
    

    Note the arrayToPtr and ptrToArray functions here ... they are the ones doing the work of passing / returning array.

提交回复
热议问题