Answer the question
In order to leave comments, you need to log in
What is the best way to create a wrapper object (without methods) in a NodeJS C++ module?
I have some C++ class, more precisely v8::CpuProfileNode , and at the moment I'm refactoring the v8-profiler project I inherited.
The current wrapper implementation declares each property as a get property, and describes the corresponding get method:
Persistent<ObjectTemplate> ProfileNode::node_template_;
void ProfileNode::Initialize() {
node_template_ = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
node_template_->SetInternalFieldCount(1);
node_template_->SetAccessor(String::New("functionName"), ProfileNode::GetFunctionName);
...
}
Handle<Value> ProfileNode::GetFunctionName(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
Local<Object> self = info.Holder();
void* ptr = self->GetPointerFromInternalField(0);
Handle<String> fname = static_cast<CpuProfileNode*>(ptr)->GetFunctionName();
return scope.Close(fname);
}
...
Handle<Value> ProfileNode::New(const CpuProfileNode* node) {
HandleScope scope;
if (node_template_.IsEmpty()) {
ProfileNode::Initialize();
}
Local<Object> obj = node_template_->NewInstance();
obj->SetPointerInInternalField(0, const_cast<CpuProfileNode*>(node));
return scope.Close(obj);
}
//Persistent<ObjectTemplate> ProfileNode::node_template_;
//delete Initialize method
//delete GetFunctionName method
Handle<Value> ProfileNode::New(const CpuProfileNode* node) {
HandleScope scope;
Local<Object> obj = Object::New();
obj->Set(String::New("functionName"), node->GetFunctionName());
...
//Указатель не нужен - методов не будет
//obj->SetPointerInInternalField(0, const_cast<CpuProfileNode*>(node));
return scope.Close(obj);
}
Answer the question
In order to leave comments, you need to log in
If you don’t need getters or setters, then the approach to immediately determine the value of the property
is the most normal one.
To make the code look nicer, I recommend immediately using
the v8-convert (aka cvv8) library https://code.google.com/p/v8-juice /wiki/V8Convert
examples:
https://code.google.com/p/v8-juice/wiki/ConvertingTypes
I remember with horror what the code looked like without CastToJS and CastFromJS functionality
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question