Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save calderaro/e8017fc73da252d0544548fdece6a5bc to your computer and use it in GitHub Desktop.
Save calderaro/e8017fc73da252d0544548fdece6a5bc to your computer and use it in GitHub Desktop.
Return a String from C++ to WASM
// C++ bit . save it in an example.cpp file
#include "emscripten.h"
extern "C" {
inline const char* cstr(const std::string& message) {
char * cstr = new char [message.length()+1];
std::strcpy (cstr, message.c_str());
return cstr;
}
EMSCRIPTEN_KEEPALIVE
const char* getAMessage() {
return cstr("oh hai there!");
};
}
//create the HTML / JS bit
<script src="./a.out.js"></script>
<script>
Module.onRuntimeInitialized = async _ => {
const api = {
message: Module.cwrap('getAMessage', 'string', []),
};
console.log(api.message());
};
</script>
// compile with
emcc -s EXTRA_EXPORTED_RUNTIME_METHODS='["cwrap"]' -std=c++11 example.cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment