title: How to pass a buffer pointer to a WebAssembly function
body: <p>Inside the excellent <a href="https://wasdk.github.io/WasmFiddle/" rel="nofollow noreferrer">WasmFiddle</a> tool, I'm using this WASM function:</p>
  <pre><code>int f(char *in, char *out, int len) { 
      for (int i = 0; i &lt; len; i++) {
          out[4*i] = in[i];
          out[4*i+1] = in[i];
          out[4*i+2] = in[i];
          out[4*i+3] = 255;
      }   
      return 0;
  }
  </code></pre>
  <p>and this JS code:</p>
  <pre><code>var wasmModule = new WebAssembly.Module(wasmCode);
  var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);
  var width = 1000, height = 1000;
  var array = new Uint8Array(width*height).fill().map(() =&gt; Math.round(Math.random() * 255)); // random values
  var rgba = new Uint8ClampedArray(4*width*height);
  wasmInstance.exports.f(array, rgba, width*height);
  </code></pre>
  <p>The last line is an error because it fails to pass the reference/pointer of <code>array</code> and <code>rgba</code>.</p>
  <p>How to do this, in particular in this WasmFiddle environment?</p>
  <p>I've read <a href="https://stackoverflow.com/questions/40083041/pass-array-to-c-function-with-emscripten">Pass array to C function with emscripten</a>, <a href="https://stackoverflow.com/questions/17883799/how-to-handle-passing-returning-array-pointers-to-emscripten-compiled-code">How to handle passing/returning array pointers to emscripten compiled code?</a>, <a href="https://stackoverflow.com/questions/41875728/pass-a-javascript-array-as-argument-to-a-webassembly-function">Pass a JavaScript array as argument to a WebAssembly function</a> but I don't see how to apply this here.</p>
  <hr />
  <p>Attempt #1 inspired from <a href="https://rob-blackbourn.github.io/blog/webassembly/wasm/array/arrays/javascript/c/2020/06/07/wasm-arrays.html" rel="nofollow noreferrer">Passing arrays between wasm and JavaScript</a>:</p>
  <pre><code>var wasmModule = new WebAssembly.Module(wasmCode);
  var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);
  var width = 10, height = 10;
  var array = new Uint8Array(wasmInstance.exports.memory.buffer, 0, width*height).fill().map(() =&gt; Math.round(Math.random() * 255)); // random values
  var rgba = new Uint8ClampedArray(wasmInstance.exports.memory.buffer, width*height, 4*width*height);
  wasmInstance.exports.f(array.byteOffset, rgba.byteOffset, width*height);
  log(array);
  log(rgba);
  </code></pre>
  <p>but in the result we see <code>[0, 0, 0, 255, 0, 0, 0, 255, ...]</code>: other values haven't been modified as expected. Also when increasing the size to width and height = 1000, it doesn't work anymore.</p>