title: Pass a JavaScript array as argument to a WebAssembly function
body: <p>I would like to test WebAssembly for doing some complex array calculations. </p>
  
  <p>So I've written a simple C++ function adding two <code>int</code> arrays containing 3 elements each  :</p>
  
  <pre><code>// hello.cpp
  extern "C" {
  
  void array_add(int * summed, int* a, int* b) {
    for (int i=0; i &lt; 3; i++) {
      summed[i] = a[i] + b[i];
    }
  }
  
  }
  </code></pre>
  
  <p>And compiled this with :</p>
  
  <p><code>emcc hello.cpp -s WASM=1 -s "MODULARIZE=1" -s "EXPORT_NAME='HELLO'" -s "BINARYEN_METHOD='native-wasm'" -s "EXPORTED_FUNCTIONS=['_array_add']" -o build/hello.js</code></p>
  
  <p>Which generates among others, a <code>js</code> and a <code>wasm</code> file. I load these with the following html page :</p>
  
  <pre><code>&lt;!doctype html&gt;
  &lt;html lang="en-us"&gt;
    &lt;head&gt;
      &lt;meta charset="utf-8"&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;
      &lt;script type="text/javascript" src="build/hello.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;
        function reqListener () {
          // Loading wasm module
          var arrayBuffer = oReq.response
          HELLO['wasmBinary'] = arrayBuffer
          hello = HELLO({ wasmBinary: HELLO.wasmBinary })
  
          // Calling function
          var result = new Int32Array(3)
          var a = new Int32Array([1, 2, 3])
          var b = new Int32Array([4, 5, 2])
          hello._array_add(result, a, b)
          console.log('result', result)
        }
  
        var oReq = new XMLHttpRequest();
        oReq.responseType = "arraybuffer";
        oReq.addEventListener("load", reqListener);
        oReq.open("GET", "build/hello.wasm");
        oReq.send();
      &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
  
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>But somehow, the <code>result</code> array is always <code>[0, 0, 0]</code>. </p>
  
  <p>I have tried a variety of things, including calling the function with <code>ccall()</code> (see <a href="https://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#interacting-with-code-ccall-cwrap" rel="noreferrer">emscripten docs</a> ) and it seems that I cannot get an array passed as argument of my wasm compiled function. </p>
  
  <p>For example, with the following C++ function : </p>
  
  <pre><code>extern "C" {
  
  int first(int * arr) {
    return arr[0];
  }
  
  }
  </code></pre>
  
  <p>Result when called in JavaScript is a random-ish integer, instead of the expected value from the array I passed as argument.</p>
  
  <p>What am I missing?</p>
  
  <p><strong>NB</strong> : I know pretty much nothing about C++, so all apologies if this is a beginner question related to my C++ ignorance ...</p>