Skip to content

Instantly share code, notes, and snippets.

@ingride
Last active May 24, 2023 17:44
Show Gist options
  • Save ingride/7bb61483127d1f6d85a35d772b589090 to your computer and use it in GitHub Desktop.
Save ingride/7bb61483127d1f6d85a35d772b589090 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
@Mormert
Copy link

Mormert commented Feb 26, 2022

This has a memory leak?

@VirtualPirate
Copy link

I think there is a memory leak here. Can anyone explain how this code is not causing a memory leak

@qknight
Copy link

qknight commented May 24, 2023

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