Skip to content

Instantly share code, notes, and snippets.

@krhoyt
Created January 28, 2022 05:56
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 krhoyt/c9de4c33f9e45db3f4473cb46e9aed83 to your computer and use it in GitHub Desktop.
Save krhoyt/c9de4c33f9e45db3f4473cb46e9aed83 to your computer and use it in GitHub Desktop.
WebAssembly (C++) in a Web Worker
#include <iostream>
#include <string>
#include "dog.h"
#include "emscripten/bind.h"
using namespace emscripten;
using namespace std;
Dog::Dog( string n ): name( n ) {}
string Dog::getName() {
return name;
}
void Dog::setName( string n ) {
name = n;
}
string Dog::bark() {
return "Hello, " + name;
}
EMSCRIPTEN_BINDINGS ( c ) {
class_<Dog>( "Dog" )
.constructor<string>()
.function( "bark", &Dog::bark )
.function( "getName", &Dog::getName )
.function( "setName", &Dog::setName );
}
#ifndef DOG_H
#define DOG_H
#include <string>
using std::string;
class Dog {
string name;
public:
Dog( string n );
string getName();
void setName( string n );
string bark();
};
#endif
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dog</title>
</head>
<body>
<p></p>
<script>
const label = document.querySelector( 'p' );
const solver = new Worker( 'worker.js' );
solver.addEventListener( 'message', ( evt ) => {
if( evt.data.type === 'init' ) {
solver.postMessage( {type: 'name', value: 'Kevin'} );
} else if( evt.data.type === 'name' ) {
solver.postMessage( {type: 'bark'} );
} else if( evt.data.type === 'bark' ) {
console.log( evt.data.value );
label.innerText = evt.data.value;
}
} );
solver.postMessage( {type: 'init'} );
</script>
</body>
</html>
emcc --bind -Oz dog.cc -o dog.js \
-s WASM=1 -s NO_EXIT_RUNTIME=1 -s "EXPORTED_RUNTIME_METHODS=['addOnPostRun']" \
|| exit 1
let dog = null;
addEventListener( 'message', ( evt ) => {
if( evt.data.type === 'init' ) {
console.log( 'WORKER: INIT' );
importScripts( 'dog.js' );
Module.addOnPostRun( () => {
dog = new Module.Dog( 'Snoopy' );
console.log( dog );
} );
postMessage( {type: 'init'} );
} else if( evt.data.type === 'bark' ) {
console.log( 'WORKER: BARK' );
postMessage( {type: 'bark', value: dog.bark()} )
} else if( evt.data.type === 'name' ) {
console.log( 'WORKER: NAME' );
dog.setName( evt.data.value );
postMessage( {type: 'name'} );
}
}, false );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment