Y
Y
Yuri Puzynya2014-05-28 14:06:48
C++ / C#
Yuri Puzynya, 2014-05-28 14:06:48

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);
}

As a result, if you describe each property in this way, it becomes monstrous .
I want to just create an object with properties:
//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);
}

As you can see, it's much shorter, and the result seems to be the same. Is the below example burdensome in terms of memory or performance?
Am I allowed to write such an implementation, or are get methods preferable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Starkov, 2014-07-27
@3y3

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 question

Ask a Question

731 491 924 answers to any question