Node v0.12 Addons and V8: Returning new objects from exposed functions

63 views
Skip to first unread message

blazs

unread,
Sep 30, 2014, 8:25:24 AM9/30/14
to nod...@googlegroups.com
Hi,

suppose I have wrapped a vector TJsVec and there's a function static void multiply(const v8::FunctionCallbackInfo<v8::Value>& Args); that returns a new TJsVec, scaled by a scalar:

void TJsVec::multiply(const FunctionCallbackInfo<Value>& Args) {
  Isolate* Isolate = Isolate::GetCurrent();
  HandleScope Scope(Isolate);
  
  /* error checking -- make sure Args.Length() >= 1 and Args[0] is a number */ 
  TJsVec* JsVec = ... /* unwraps the object */ 
  const double Scalar = Args[0]->NumberValue();
  TFloatVector ResV; // ResV = JsVec->Vec * Scalar 
   ... /* scales JsVec->Vec by scalar using internal linear algebra library */
  
   TJsVec* JsResV = new TJsVec(ResV);
   JsResV->Wrap(Args.Holder()); // (1)
   // (2) 
   Args.GetReturnValue().Set(JsResV); // (3)
}

Note that TJsVec is derived from node::ObjectWrap, i.e. we have class TJsVec : public node::ObjectWrap { ... };.

I have several questions regarding this code:
 (*) What exactly does the line JsResV->Wrap(Args.Holder()) do? Why do we pass it Args.Holder()?
 (*) What does Args.GetReturnValue().Set(JsResV); do? 
 (*) And, most important, suppose I executed Javascript function in the place (2). Could V8 garbage-collected JsResV? I.e. is object elligible for delition at (2) -- immediately after creation and before the function "returns" it in (3)? 

Furher, should I move the line (3) immediately after creating the object? 

Blaz.
Reply all
Reply to author
Forward
0 new messages