Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to return an object that has a child object? #101

Open
travbid opened this issue Jan 11, 2018 · 1 comment
Open

How to return an object that has a child object? #101

travbid opened this issue Jan 11, 2018 · 1 comment

Comments

@travbid
Copy link

travbid commented Jan 11, 2018

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.

@TanninOne
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants