handle native function that returns a struct pointer, and pass the struct pointer back to webasm

32 views
Skip to first unread message

CebWebXer

unread,
Sep 14, 2020, 6:51:24 AM9/14/20
to emscripten-discuss
I had successfuly, built a 3rd party library in webasm and I am trying to test it.
however I am stuck on how to proceed as I cant find documentation or tutorial related to it.

the library I ported is initialized by calling a Create() function and returns a struct pointer like a context, and this struct pointer is passed everytime a function on that libraryy is called.

I am confuse on how to handle this in webasm as the returning struct pointer is neither used outside of the library but just recieved and passed thru.
I have tried settingthe return value as 'number' in the call to initialize method and just pass back these number to the next method but to no lock.

here is a sample mini code I made

C++
void* EMSCRIPTEN_KEEPALIVE InitializeLibrary(){
SomeStruct s;
 s.k = 18;
 s.t = 21;
return (void*)&s;
}

int EMSCRIPTEN_KEEPALIVE Add(void* b) {
SomeStruct* bg = (SomeStruct*)b;
return bg->k + bg->t;
}

and in Javascript/nodejs side

const ptr = Module.ccall("InitializeLibrary", 'number', null);
const result = Module.ccall("Add", 'number', ['number'],[ptr]);
console.log(result);

to no avail,
How to effectively approach this?

I have yet to try (and will try next), creating a C/C++ adapter that will serve as the middleman between the library and JS instead and keep the pointer/context in there, but im not sure if its possible.

Any help is appreaciated.

Floh

unread,
Sep 15, 2020, 6:17:39 AM9/15/20
to emscripten-discuss
That approach should work, but your code has a simple bug that isn't WASM specific:

void* EMSCRIPTEN_KEEPALIVE InitializeLibrary(){
SomeStruct s;
 s.k = 18;
 s.t = 21;
return (void*)&s;
}

You're returning the address of a stack variable (SomeStruct s). When your function returns that struct will be gone and the pointer you return will point to some random address which previously was occupied by "SomeStruct s" (e.g. the pointer is "dangling" now).

You need to make 's' outlive the function, either by allocating via malloc, or turning it into a global variable via 'static' or moving the struct out of the function into the "global scope".

Floh

unread,
Sep 15, 2020, 6:22:10 AM9/15/20
to emscripten-discuss
PS: you should actually get a compiler warning in this situation, even with the default warning level, see:




Reply all
Reply to author
Forward
0 new messages