Forked from ingride/gist:7bb61483127d1f6d85a35d772b589090
Created
May 8, 2021 21:00
-
-
Save calderaro/e8017fc73da252d0544548fdece6a5bc to your computer and use it in GitHub Desktop.
Return a String from C++ to WASM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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