User Tools

Site Tools


Sidebar

General

Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm


Martin Christen

View Martin Christen's profile on LinkedIn


Twitter

Timeline of @MartinChristen

MartinChristen avatar

RT @TFConsult: Celebrating 100th birthday of #physicist #RichardFeynman: The marvellous #Feynman lectures on #physics: https://t.co/81as7mN
About 1 week, 4 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @sergerey: Had a fantastic time giving our workshop on Spatial Data Science with PyData at @GeoPythonConf with @levijohnwolf. Looking f…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @fridex: Everything has an end even such an excellent conference #GeoPythonConf in Basel. Thanks to organizers for such an outstanding c…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)
node:tutorial12

Node.js Tutorials - Series 1

Tutorial 1.2: Creating Node-Buffers in C++

Node-Buffers are written in JavaScript (source available at: https://github.com/joyent/node/blob/master/lib/buffer.js). Therefore it is a little bit tricky to create a buffer from C++.

First get the handle of the global object:

Local<Object> globalObj = Context::GetCurrent()->Global();

Then retrieve the constructor of the Buffer object:

Local<Function> bufferConstructor = 
      Local<Function>::Cast(globalObj->Get(String::New("Buffer")));

Then set the arguments for the constructor. First the handle, second the length and third the offset where to start, usually this is 0.

  Handle<Value> constructorArgs[3] = { slowBuffer->handle_, 
                           Integer::New(length), 
                           Integer::New(0) };

Finally call the constructor, now we have a valid buffer object.

Local<Object> actualBuffer = 
       bufferConstructor->NewInstance(3, constructorArgs);

Full Code

Handle<Value> CreateBuffer(const Arguments& args)
{
  HandleScope scope;
		
  const char *data = "Hello world! This is data...";
  int length = strlen(data);
  
  node::Buffer *slowBuffer = node::Buffer::New(length);
  memcpy(node::Buffer::Data(slowBuffer), data, length);
  	
  // get handle to the global object
  Local<Object> globalObj = Context::GetCurrent()->Global();
  // Retrieve the buffer constructor function 
  Local<Function> bufferConstructor = 
       Local<Function>::Cast(globalObj->Get(String::New("Buffer")));
  // use buffer constructors with 3 arguments: 
  //   (1) handle of buffer 
  //   (2) length of buffer 
  //   (3) offset in buffer (where to start)
  Handle<Value> constructorArgs[3] = { slowBuffer->handle_, 
                           Integer::New(length), 
                           Integer::New(0) };
  // call the buffer-constructor
  Local<Object> actualBuffer = 
       bufferConstructor->NewInstance(3, constructorArgs);

  return scope.Close(actualBuffer);  
}

References:


node/tutorial12.txt · Last modified: 2013/09/16 22:48 by mchristen