Last active
March 15, 2016 21:05
-
-
Save lakenen/5640386 to your computer and use it in GitHub Desktop.
Emscripten JS/C++ Proxy Example (http://stackoverflow.com/a/16725147/494954)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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_getFoo', '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); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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