Hi, 

I want to call a C function dealing with arrays from Javascript.

The function is created with emscripten. I also want to create JS
functions handling native JavaScript arrays, for example a
Uint8Array.

>From my understanding I have to create a JS wrapper allocating an
array in the heap, copy the data from the JS array, process the data
through the emscripten generated function, and finally copy the
processed data back to a JS array.

Consider this example:

C function:
void multiply_array(uint8_t factor, uint8_t *buf, size_t buf_size)
{
    for (int i = 0; i < buf_size; i++) {
        buf[i] = factor * buf[i];
    }
}

JS wrapper:
multiply_by_factor = function(u8array, factor) {
   // need to get the array pointer, u8array is Uint8Array

   // Get data byte size, allocate memory on Emscripten heap, and get pointer
   var dataPtr = Module._malloc(u8array.length);

   // allocate new Uint8Array in the Emscripten heap (directly accessed from 
Module.HEAPU8)
   var dataHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, u8array.length);

   // copy data to the heap
   dataHeap.set(u8array);

   // Call function and process data inplace
   _multiply_array(factor, dataPtr, u8array.length);
   var result = new Uint8Array(u8array.length);
   result.set(dataHeap);

   // Free memory from emscripten heap
   Module._free(dataHeap.byteOffset);
   return result;
}

This function is working fine, but I wonder if it's possible to avoid
to allocate data on the emscripten heap, in order to avoid the two
memcpy calls.

TIA

-- 
You received this message because you are subscribed to the Google Groups 
"emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to