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 @snebiker: #PlayGameLieschtel - brilliant event by Kantonsbibliothek Baselland #KBL to get kids into libraries, including family #gamede…
About 2 days, 14 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Only a handful tickets left for @PyConDE in Karlsruhe (October 24-28, 2018) - The schedule is now available at… https://t.co/Og4fp3DsoA
About 5 days, 7 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

IAMCP & @swissmade_sw Augmented Reality event just started https://t.co/bdREI6lJM4 #ar #AugmentedReality #Basel… https://t.co/9KpsdU3fvM
About 6 days, 13 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