Skip to content

Instantly share code, notes, and snippets.

@binji
Created March 28, 2020 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binji/c407a4ce6b6a33e456ccc7e9c11f03b5 to your computer and use it in GitHub Desktop.
Save binji/c407a4ce6b6a33e456ccc7e9c11f03b5 to your computer and use it in GitHub Desktop.
WebAssembly memory reading demo
emcc test.c -o test.js -s EXPORTED_FUNCTIONS='["_get", "_increment"]'
int my_var = 42;
int* get(void) { return &my_var; }
void increment(void) { my_var++; }
<!doctype html>
<script src="test.js"></script>
<p>my_var: ???</p>
<button>increment</button>
<script>
let p = document.querySelector('p');
let button = document.querySelector('button');
// Click the button to increment the variable. <p> won't be updated immediately.
button.addEventListener('click', () => { _increment(); });
// Wait for emscripten to initialize the module.
addOnInit(() => {
// Read the address of my_var.
let addr = _get();
// Every half second...
setInterval(() => {
// Read the value of my_var from memory.
let value = HEAP32[addr>>2];
// Update the <p> element.
p.textContent = `my_var: ${value}`;
}, 500);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment