3

I have an array type of uint8_t in C. A function called getResultArray will return this array. How can I get this array in JavaScript?

uint8_t * getResultBuffer() { return resultBuffer }

1 Answer 1

4

The pointer returned from the C function is an offset into the ArrayBuffer that Emscripten uses to represent memory. For viewing as uint8_t, access the memory using Module.HEAPU8.

Here is an example, using em++:

fill_array.cpp:

#include "stdint.h"

extern "C" {
    uint8_t* fill_array(int n);
}

uint8_t* fill_array(int n) {
    uint8_t* arr = new uint8_t[n];
    for(uint8_t i=0;i<n;++i)
        arr[i] = i;
    return arr;
}

index.html:

<!doctype html>
<html>
<body>
    <script>
        var Module = {
          onRuntimeInitialized: function() {
            var fill_array = Module.cwrap('fill_array', 'number', [])
            var n = 16;
            var ptr_from_wasm = fill_array(n);
            var js_array = Module.HEAPU8.subarray(ptr_from_wasm, ptr_from_wasm + n);
            alert(js_array);
          },
        };
    </script>
    <script async type="text/javascript" src="index.js"></script>
</body>
</html>

Results in the following:

0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15

For this to work, you'll need to add the following arguments to em++:

-s EXPORTED_FUNCTIONS='["_fill_array"]' -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]'

See full source code in This repo

Sign up to request clarification or add additional context in comments.

1 Comment

What if the array is in stack? Can you still use HEAP8 to access it in JS?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.