DEV Community

Passing strings from C++ to JavaScript in Web Assembly

Bryan Hughes on March 21, 2019

I'm moving right along with my experiments of getting the messaging stack of my wireless LED control system running in Node.js via Web Assembly (WA...
Collapse
 
golinvauxb profile image
Benjamin Golinvaux

I would be careful not to use "-s ERROR_ON_UNDEFINED_SYMBOLS=0" for too long, for this may turn build-time errors into run-time ones! The --js-library flag can be used for the JS glue code. You are certainly aware of this, but I think beginners should understand the risk :)

Collapse
 
nebrius profile image
Bryan Hughes

Good point about the dangers of -s ERROR_ON_UNDEFINED_SYMBOLS=0, thanks!

I'll confess, I haven't explored using the --js-library flag yet. A quick read suggested it wouldn't do what I needed it to do, but I also may just not have read deeply into it enough.

Collapse
 
golinvauxb profile image
Benjamin Golinvaux

The thing is:
if, in your C++ code, you define something as:

extern int GetFoo();

Then, if you build the code, you'll get an undefined symbol error, UNLESS this function can be "seen" by emscripten. It can only see it if you put it in a js file that it knows of. That is, a file that is passed to the --js-library flag.

What I usually do is something like:

C++: extern "C" void SomeFunction();

JS (in library.js) : SomeFunction : function() { _SomeFunction() }

And _SomeFunction is declared in the JavaScript project where I load the wasm module in.

You can find more details here:

emscripten.org/docs/porting/connec...

HTH

Collapse
 
nebrius profile image
Bryan Hughes

I added a note in the text itself warning folks to be careful about undefined symbols. Thanks again!

Collapse
 
rw251 profile image
Richard Williams

Great article. Minor typo - should be strlen(str) rather than strlen(s).

Collapse
 
nebrius profile image
Bryan Hughes

Nice catch, and thanks for letting me know. It's fixed now.