Skip to content

Instantly share code, notes, and snippets.

@tbfleming
Last active November 11, 2018 11:47
Show Gist options
  • Save tbfleming/d9f362c23d17a9199d272f51acbcc32a to your computer and use it in GitHub Desktop.
Save tbfleming/d9f362c23d17a9199d272f51acbcc32a to your computer and use it in GitHub Desktop.
cib demo: C++ and JS calling into each other
#include <emscripten.h>
int counter = 0;
bool running = false;
// Defined in javascript
extern "C" void enableButtons();
extern "C" void setCounterValue(int);
// Called by javascript
extern "C" void run(bool r) {
running = r;
}
// Called by javascript
extern "C" void reset() {
counter = 0;
setCounterValue(counter);
}
void timer(void *) {
if(running)
setCounterValue(counter++);
emscripten_async_call(timer, nullptr, 200);
}
int main() {
enableButtons();
timer(nullptr);
}
%init-scripts%
<button id="run" onclick="wasmExports.run(true)" disabled>Run</button>
<button id="stop" onclick="wasmExports.run(false)" disabled>Stop</button>
<button id="reset" onclick="wasmExports.reset()" disabled>Reset</button>
<br />Counter value:
<span id="counter">0</span>
<script>
wasmImports = {
enableButtons() {
document.getElementById('run').disabled = false;
document.getElementById('stop').disabled = false;
document.getElementById('reset').disabled = false;
},
setCounterValue(v) {
document.getElementById('counter').textContent = v;
},
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment