Skip to content

Instantly share code, notes, and snippets.

@lakenen
Last active March 15, 2016 21:05

Revisions

  1. lakenen revised this gist May 24, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion helloworld-proxy.js
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,7 @@
    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']);
    var HW_getX = Module.cwrap('HW_getX', 'number', ['number']);

    function HelloWorld() {
    this.ptr = HW_constructor();
  2. lakenen created this gist May 23, 2013.
    6 changes: 6 additions & 0 deletions build.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    #!/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
    21 changes: 21 additions & 0 deletions helloworld-proxy.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    // 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);
    };
    30 changes: 30 additions & 0 deletions helloworld.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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;
    }
    };