Skip to content

Instantly share code, notes, and snippets.

@lakenen
Last active March 15, 2016 21:05
Show Gist options
  • Save lakenen/5640386 to your computer and use it in GitHub Desktop.
Save lakenen/5640386 to your computer and use it in GitHub Desktop.
Emscripten JS/C++ Proxy Example (http://stackoverflow.com/a/16725147/494954)
#!/bin/bash
emcc helloworld.cpp -o helloworld.js \
-s EXPORTED_FUNCTIONS="['_HW_constructor','_HW_destructor','_HW_setX','_HW_getX']"
cat helloworld-proxy.js >> helloworld.js
// get references to the exposed proxy functions
var HW_constructor = Module.cwrap('HW_constructor', 'number', []);
var HW_destructor = Module.cwrap('HW_destructor', null, ['number']);
var HW_setX = Module.cwrap('HW_setX', null, ['number', 'number']);
var HW_getX = Module.cwrap('HW_getX', 'number', ['number']);
function HelloWorld() {
this.ptr = HW_constructor();
}
HelloWorld.prototype.destroy = function () {
HW_destructor(this.ptr);
};
HelloWorld.prototype.setX = function (x) {
HW_setX(this.ptr, x);
};
HelloWorld.prototype.getX = function () {
return HW_getX(this.ptr);
};
class HelloWorld
{
int x;
public:
HelloWorld() { x = 0; }
~HelloWorld() {}
void setX(int v) { x = v; }
int getX() { return x; }
// ...
};
//compile using "C" linkage to avoid name obfuscation
extern "C" {
//constructor, returns a pointer to the HelloWorld object
void *HW_constructor() {
return new HelloWorld();
}
void HW_setX(HelloWorld *hw, int x) {
hw->setX(x);
}
int HW_getX(HelloWorld *hw) {
return hw->getX();
}
void HW_destructor(HelloWorld *hw) {
delete hw;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment