Search code examples
c++node.jswebassembly

How to run C++ code in WebAssembly and capture stdout?


Give this program em C++

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

How can I compile it to WebAssembly and capture stdout? Would it be possible to limit the use of memory and other resources during execution, like a sandbox, maybe using the isolated-vm project?


Solution

  • The easiest way to run the code would be to compile it with Emscripten:

    emcc main.cpp -o main.js -s WASM=1 -s NO_EXIT_RUNTIME=1 -s EXPORTED_RUNTIME_METHODS='["cwrap"]'
    

    I am not sure how you want to run it, but you tagged the question with node.js, so this is how to run it in node:

    node main.js
    

    You can check the Emscripten documentation in order to better understand every flag, but basically the command above compiles the code to wasm (Emscripten is a C to JavaScript compiler at origins).

    As for isolated-vm, the resulting code is javascript + wasm, so in theory, any method that you use to run javascript code with node should work. The code isn't any different from other javascript code that calls to webassembly.