porente
porente

Reputation: 443

emscripten read javascript arrayBuffer in C

This code is incorrect but it tells what I am trying to do

char* p = EM_ASM(
    var a = new ArrayBuffer(8);
    return a;
);

What is the correct way of getting a C pointer of that javascript arrayBuffer?
I only want to read the arrayBuffer not write

Upvotes: 2

Views: 1818

Answers (1)

John Sharp
John Sharp

Reputation: 811

As far as I'm aware, there's no direct way of returning an array from some inline JavaScript (although there is a way of returning read-only arrays from JavaScript wrapped C functions, see this answer). What you can do instead is malloc space for the array in a C function, pass the address to the inline Emscripten, and use the Emscripten JavaScript function writeArrayToMemory to copy your JavaScript array into the malloced memory. Something like this...

char *a = malloc(4);

EM_ASM_INT({
    var v1 = new Uint8Array([2,4,6,8]);

    writeArrayToMemory(v1, $0)
    }, a);

printf("the array is [%d, %d, %d, %d]\n", a[0], a[1], a[2], a[3]);

Upvotes: 4

Related Questions