问题
I'm working on a node.js/io.js native plugin, and I need to create a new native object from an async callback.
Using the nan helpers, I've got something that looks like:
class MyObject : public node::ObjectWrap
{ /* definition */ };
class MyWorker : public NanAsyncWorker
{
bool varForMyObject;
virtual void Execute() {/* do stuff and sets varForMyObject */}
virtual void HandleOKCallback() {
NanScope();
MyObject* obj = new MyObject(varForMyObject);
Local<Value> argv[] = {
NanNull(),
obj // ???
};
callback->Call(2, argv);
}
};
I cannot figure out how to wrap the object without having access to the args parameters.
Help?
回答1:
You should create javascript object manually, example:
//some_class.h
class SomeClass {
public:
std::string id;
int value;
SomeClass() {};
SomeClass(std::string id, int value): id(id), value(value) {};
static SomeClass *unpack(v8::Isolate *isolate, const v8::Local<v8::Object> object) {
using namespace v8;
SomeClass *p = new SomeClass();
Local<Value> _id = object->Get(String::NewFromUtf8(isolate, "id"));
String::Utf8Value utf8String(_id);
p->id = std::string(*utf8String);
p->value = static_cast<int>(object->Get(String::NewFromUtf8(isolate, "value"))->NumberValue());
return p;
}
static v8::Local<v8::Object> pack(v8::Isolate *isolate, const SomeClass *object) {
using namespace v8;
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "id"), String::NewFromUtf8(isolate, object->id.c_str()));
obj->Set(String::NewFromUtf8(isolate, "value"), Integer::New(isolate, object->value));
return obj;
};
}
then in your worker:
class MyObject : public node::ObjectWrap
{ /* definition */ };
class MyWorker : public NanAsyncWorker
{
virtual void Execute() {/* do stuff and sets varForMyObject */}
virtual void HandleOKCallback() {
NanScope();
SomeClass *c = new SomeClass("id", 123);
Local<Value> argv[] = {
NanNull(),
SomeClass::pack(v8::Isolate::GetCurrent(), c)
};
callback->Call(2, argv);
}
};
来源:https://stackoverflow.com/questions/29992369/how-to-return-a-new-object-from-nanasyncworker