Last active
May 24, 2023 17:44
-
-
Save ingride/7bb61483127d1f6d85a35d772b589090 to your computer and use it in GitHub Desktop.
Return a String from C++ to WASM
This file contains 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 |
Thank you! :) It really saved my day.
This has a memory leak?
I think there is a memory leak here. Can anyone explain how this code is not causing a memory leak
See futher discussion emscripten-core/emscripten#6433
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow this appeared on my mobile chrome news on start page, didn't know I'd see gist there