Skip to content

Instantly share code, notes, and snippets.

@AlexPerrot
Created March 15, 2017 14:38
Show Gist options
  • Select an option

  • Save AlexPerrot/5d8a3aa0eacf7f3de5478ec1164c834e to your computer and use it in GitHub Desktop.

Select an option

Save AlexPerrot/5d8a3aa0eacf7f3de5478ec1164c834e to your computer and use it in GitHub Desktop.
Embind references test
#include <emscripten/bind.h>
#include <functional>
class ByRef {
int field=0;
public:
ByRef& getRef() {return *this;}
ByRef* getPtr() {return this;}
const ByRef& getConstRef() const {return *this;}
int getValue() const {return field;}
void incr() {field++;}
};
void incrRef(ByRef &r) {r.incr();}
void incrPointer(ByRef *p) {p->incr();}
ByRef& passthrough(ByRef& r) {return r;}
ByRef copy(ByRef& r) {return r;}
int getValueByConstRef(const ByRef& r) {return r.getValue();}
int getValueByRef(ByRef& r) {return r.getValue();}
int getValueByPointer(ByRef* r) {return r->getValue();}
template <typename T, T> struct proxy;
template <typename T, typename R, typename ...Args, R (T::*mf)(Args...)>
struct proxy<R (T::*)(Args...), mf>
{
using ptr = typename std::add_pointer<typename std::remove_reference<R>::type>::type;
static ptr call(T & obj, Args &&... args)
{
return &((obj.*mf)(std::forward<Args>(args)...));
}
};
#define RETURN_POINTER(value) &proxy<decltype(value), (value)>::call
EMSCRIPTEN_BINDINGS(valueMethod) {
using namespace emscripten;
function("incrRef", &incrRef, references_as_pointers());
function("incrPointer", &incrPointer, allow_raw_pointers());
function("pass", &passthrough, references_as_pointers());
function("copy", &copy);
function("getValueByRef", &getValueByRef);
function("getValueByPointer", &getValueByPointer, allow_raw_pointers());
function("getValueByConstRef", &getValueByConstRef);
class_<ByRef>("Ref").constructor()
.function("ref",&ByRef::getRef, references_as_pointers())
.function("ptr",RETURN_POINTER(&ByRef::getRef), allow_raw_pointers())
.function("getPtr", &ByRef::getPtr, allow_raw_pointers())
.function("constRef", &ByRef::getConstRef)
.function("value",&ByRef::getValue)
.function("incr",&ByRef::incr)
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment