Emscripten - Getting a string from JavaScript

Author: thothonegan
Tags: c++ emscripten

Quick little helper today. Spent a long time searching for this and found way too many half-answers.

So you’re using emscripten, and you want to call a javscript function, say stackTrace. This returns a javascript string, but you need to use it from c++! What to do?

Simple!

 std::string varName = "v";
    
int length = EM_ASM_INT ({
  return eval(
    'Module.lengthBytesUTF8(' + Module.Pointer_stringify($0) + ')'
  )}, varName.c_str()
);
    
std::string s;
s.reserve (length+1);
s.resize (length);
    
EM_ASM_ ({
  eval('Module.stringToUTF8 ('
    + Module.Pointer_stringify($0) + ', $1, $2)'
  )}, varName.c_str(),
    s.c_str(), s.size()
);

// s now has the string in UTF8 format