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

@PostFinance If you are interested in Python - the @EuroPython conference, largest Python conf in Europe with over… https://t.co/TBgyaePA6U
About 3 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @opengeospatial: OGC seeks public comment on update to GeoTIFF standard. This minor revision to GeoTIFF enables the use of newer coordin…
About 5 days, 12 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @europython: Early-bird tickets sold out in less than 10 minutes. Amazing ! Sales were so fast, we ended up selling 275 tickets instead…
About 6 days, 15 hours 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