title: Is there a more efficient way to return arrays from C++ to javascript?
body: <p>To pass typed array from emscripten'ed C++ to javascript I came up with this code</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;emscripten/bind.h&gt;
  #include &lt;emscripten/val.h&gt;
  
  auto test(const emscripten::val &amp;input) {
    const auto data = emscripten::convertJSArrayToNumberVector&lt;float&gt;(input); // copies data
  
    // generate output in some form
    std::vector&lt;float&gt; output = { 1, 2, 3 };
    // make a typed array view of the output
    emscripten::val view{ emscripten::typed_memory_view(output.size(), output.data()) };
    // create new typed array to return
    auto result = emscripten::val::global(&quot;Float32Array&quot;).new_(output.size());
    // copy data from generated output to return object
    result.call&lt;void&gt;(&quot;set&quot;, view);
  
    return result;
  }
  
  EMSCRIPTEN_BINDINGS(KissFft) {
    emscripten::function(&quot;test&quot;, &amp;test);
  }
  </code></pre>
  <p>(build with <code>em++ test.cpp -o test.html --bind</code>)</p>
  <p>In this case there are two extra copies:</p>
  <ul>
  <li>the copy from input array to wasm memory, as far as I understand it's unavoidable;
  <pre class="lang-cpp prettyprint-override"><code>const auto data = emscripten::convertJSArrayToNumberVector&lt;float&gt;(input);
  </code></pre>
  </li>
  <li>the copy from wasm memory to javascript object:
  <pre class="lang-cpp prettyprint-override"><code>emscripten::val view{ emscripten::typed_memory_view(output.size(), output.data()) };
  auto result = emscripten::val::global(&quot;Float32Array&quot;).new_(output.size());
  result.call&lt;void&gt;(&quot;set&quot;, view);
  
  return result;
  </code></pre>
  </li>
  </ul>
  <p><strong>Is there a way to avoid extra copy from generated output to javascript object in the second case?</strong></p>
  <p>I'm aware of the possibility to return memory view like this:</p>
  <pre class="lang-cpp prettyprint-override"><code>std::vector&lt;float&gt; output;
  
  auto test(const emscripten::val &amp;input) {
    const auto data = emscripten::convertJSArrayToNumberVector&lt;float&gt;(input);
  
    //generate output
    return emscripten::val{ emscripten::typed_memory_view(output.size(), output.data()) };
  }
  
  EMSCRIPTEN_BINDINGS(KissFft) {
    emscripten::function(&quot;test&quot;, &amp;test);
  }
  </code></pre>
  <p>But in this case the returned object refers to the underlying memory owned by <code>output</code> static object with all the consequences, like modifying the memory on the C++ side, or even deallocating it.</p>