nbind
nbind copied to clipboard
How to return an object that has a child object?
node version: 8.9.3 nbind version: 0.3.14 OS: Ubuntu 17.10
I can't seem to pass an object from C++ to JavaScript when that object has object members.
Here's a minimal reproducible example:
hello.cc:
#include "nbind/api.h"
// header.hpp ----------
struct foo {
int x;
};
struct myParent {
foo child;
int y;
};
myParent originalFunction() {
myParent mp;
mp.child.x = 5;
mp.y = 6;
return mp;
}
// ---------------------
class foo_wrapper {
public:
foo_wrapper(foo f) { val = f; }
void toJS(nbind::cbOutput output) {
output(val.x);
}
foo val;
};
class myParent_wrapper {
public:
myParent_wrapper(myParent s) { val = s; }
void toJS(nbind::cbOutput output) {
output(foo_wrapper(val.child), val.y);
}
myParent val;
};
myParent_wrapper myFunc() {
return myParent_wrapper(originalFunction());
}
#include "nbind/nbind.h"
NBIND_CLASS(foo) {}
NBIND_CLASS(myParent) {}
NBIND_CLASS(myParent_wrapper) { construct<myParent>(); }
NBIND_CLASS(foo_wrapper) { construct<foo>(); }
NBIND_GLOBAL() { function(myFunc); }
index.js:
let nbind = require('nbind')
let binding = nbind.init()
let lib = binding.lib
class classFoo {
constructor(x) {
this.x = x;
}
fromJS(output) {
output(this.x)
}
}
class classParent {
constructor(a, b) {
this.child = a;
this.y = b;
}
fromJS(output) {
output(this.child, this.b);
}
}
binding.bind('foo_wrapper', classFoo);
binding.bind('myParent_wrapper', classParent);
console.log(lib.myFunc());
Output I expect from node ./index.js:
classParent { child: classFoo {x: 5}, y: 6 }
What I see instead:
classParent { child: foo_wrapper {}, y: 6 }
Am I doing something wrong? Any help would be appreciated.
I'm interested in this as well.
When you pass the foo_wrapper directly to output however it's toJS function is never called so you get the wrapper object in js.
I found that when you write something like output(std::vector<foo_wrapper>{ foo_wrapper(val.child) }) then it will transform the array element with toJS so you'd get an array of classFoo objects in javascript.