Node.js Addon - Creating And Returning An Object

88 views
Skip to first unread message

Jon Lederman

unread,
May 7, 2015, 10:24:38 PM5/7/15
to nod...@googlegroups.com
I have the following two wrappers listed below.  I want the Api method of B to return an A in javascript.  How do I do this?  I can’t figure out how to construct the B class from the A Api method and return it?  Any help would be greatly appreciated.

Jon

class A : public node::ObjectWrap {
public:
 static void Init(v8::Handle<v8::Object> exports);

private:
 explicit A(Thing *thing);
 ~A();

 static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
 static void Api(const v8::FunctionCallbackInfo<v8::Value>& args);
 static v8::Persistent<v8::Function> constructor;

 ESLconnection* _esl_connection;
};

#endif

class B : public node::ObjectWrap {
public:
 static void Init(v8::Handle<v8::Object> exports);



private:

 ~B();
 explicit B(ESLevent *event);

};

#endif

Ben Noordhuis

unread,
May 8, 2015, 9:46:41 AM5/8/15
to nod...@googlegroups.com
The code below should work. You mention both A from B and B from A in
your post. This code implements the former.

void B::F(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Local<v8::FunctionTemplate> function_template =
v8::FunctionTemplate::New(args.GetIsolate(), A::New);
v8::Local<v8::Function> function = function_template->GetFunction();
v8::Local<v8::Value> object_v = function->NewInstance(); // Can pass args.
if (object_v.IsEmpty()) return; // Constructor threw.
assert(object_v->IsObject()); // Should never fail.
v8::Local<v8::Object> object = object_v.As<v8::Object>();
// Do something with |object| here.
args.GetReturnValue().Set(object);
}

You may want to cache the v8::FunctionTemplate or the v8::Function in
a v8::Persistent so you don't have to recreate it all the time. Good
luck!
Reply all
Reply to author
Forward
0 new messages