Skip to content

Instantly share code, notes, and snippets.

@eendeego
Created November 28, 2012 10:26
Show Gist options
  • Save eendeego/4160350 to your computer and use it in GitHub Desktop.
Save eendeego/4160350 to your computer and use it in GitHub Desktop.
Node/V8 bindings cheat sheet

node-native-types

Sources

Arguments:

argument count

http://nodejs.org/api/addons.html

args.Length()

ok Scalars

http://nodejs.org/api/addons.html

v = args[n]->BooleanValue();
v = args[n]->NumberValue();
v = args[n]->IntegerValue();
v = args[n]->Uint32Value();
v = args[n]->Int32Value();

ok native enums

v = static_cast<EnumType>(args[n]->Uint32Value())

ok Object

Local<Object> obj = arg[n]->ToObject();

String

https://github.com/pkrumins/node-png/blob/master/src/png.cpp

ok Buffers

Local<Object> bufferObj    = args[n]->ToObject();
char*         bufferData   = Buffer::Data(bufferObj);
size_t        bufferLength = Buffer::Length(bufferObj);

ok NativeArrays

// TODO make this a macro

Local<Object>  array  = args[n]->ToObject();
Handle<Object> buffer = array->Get(String::New("buffer"))->ToObject();
unsigned int   offset = array->Get(String::New("byteOffset"))->Uint32Value();
int            length = array->Get(String::New("byteLength"))->Uint32Value();

// Actual data
ptr = (MyType*) &((char*) buffer->GetIndexedPropertiesExternalArrayData())[offset]

ok Wrapped values

http://nodejs.org/api/addons.html#addons_object_factory

MyType v = (MyType) External::Unwrap(args[n]);

Creating/Returning Objects:

ok Undefined / Null

Undefined(), Null()

ok Scalars

Boolean::New(v), True(), False()
Number::New(v)
Integer::New(v)
Uint32::New(v)
Int32::New(v)

ok native enums

Integer::New(v)

ok Objects

Local<Object> obj = Object::New();
// Set stuff (see below)

ok Buffers

Original: http://sambro.is-super-awesome.com/2011/03/03/creating-a-proper-buffer-in-a-node-c-addon/ Google Cache: http://webcache.googleusercontent.com/search?q=cache:kl2B7-72nk0J:sambro.is-super-awesome.com/2011/03/03/creating-a-proper-buffer-in-a-node-c-addon/+&cd=1&hl=en&ct=clnk&gl=pt

Buffer *slowBuffer = Buffer::New(length);
memcpy(Buffer::Data(slowBuffer), data, length);

Local<Object> globalObj = Context::GetCurrent()->Global();
Local<Function> bufferConstructor = Local<Function>::Cast(globalObj->Get(String::New("Buffer")));
Handle<Value> constructorArgs[3] = { slowBuffer->handle_, v8::Integer::New(length), v8::Integer::New(0) };
Local<Object> actualBuffer = bufferConstructor->NewInstance(3, constructorArgs);
return scope.Close(actualBuffer);

?? NativeArrays

Without data:

Handle<Object> arrayBuffer = Shell::CreateExternalArrayBuffer(length);
Arguments args = new Arguments(1, &[arrayBuffer]); // Fixme
Handle<Object> nativeArray = Shell::xyzArray(args)

With data:

Handle<Object> arrayBuffer = Shell::CreateExternalArrayBuffer(length);
Handle<Object> buffer = arrayBuffer->Get(String::New("buffer"))->ToObject();
memcpy(buffer->GetIndexedPropertiesExternalArrayData(), src, length);
Arguments args = new Arguments(1, &[arrayBuffer]); // Fixme
Handle<Object> nativeArray = Shell::xyzArray(args)

Arguments args = new Arguments(int length, Object** arguments);

Arguments... => (unsigned long length)
             => (ArrayBuffer[, offset[, length]])
Shell::Int8Array   (args)
Shell::Uint8Array  (args)
Shell::Int16Array  (args)
Shell::Uint16Array (args)
Shell::Int32Array  (args)
Shell::Uint32Array (args)
Shell::Float32Array(args)
Shell::Float64Array(args)
Shell::PixelArray  (args)

Handle<Value> arrayBuffer = Shell::CreateExternalArrayBuffer(length);

ok Wrapped values

http://nodejs.org/api/addons.html#addons_object_factory

External::Wrap(v)

Accessors

Objects

obj->Get(String::NewSymbol("key"));
obj->Get(index);
obj->Set(String::NewSymbol("key"), value);
obj->Set(index, value);

Arrays

https://developers.google.com/v8/embed

Handle<Array> array = Array::New(length);
array->Set(n, v);

Calling other native functions

Factory* factory = Isolate::Current()->factory();
Handle<FixedArray> argArray = factory->NewFixedArray(argCount);
argArray->set(i, v);
...
Handle<JSObject> arguments =
  factory->NewArgumentsObject(inlined_function, argCount);

for (int j = 0; j < js_args.argc(); j++) {
  i::Handle<i::String> arg =
      FACTORY->NewStringFromUtf8(i::CStrVector(js_args[j]));
  arguments_array->set(j, *arg);
}
i::Handle<i::JSArray> arguments_jsarray =
    FACTORY->NewJSArrayWithElements(arguments_array);

Globals

v8/samples/lineprocessor.cc

Handle<String> fun_name = String::New("Int32Array");
Handle<Value> Int32ArrayFn =
    Context::GetCurrent()->Global()->Get(fun_name);
@vibgy
Copy link

vibgy commented Sep 29, 2015

JSON Arrays can be accessed in the C++ code using the following code (applies to V8). For example: To get the 'sessions' array from 'inputJson' you can do this:

Local<Array> sessions = Local<Array>::Cast(inputJson->Get(String::NewFromUtf8(isolate, "sessions")));
int len = 0;
if (sessions->IsArray()) {
    len = sessions->Length();
    printf("length %u\n", len);
}

for (int i = 0; i < len; i++) {
    Local<Object> aSession = Local<Object>::Cast(sessions->Get(i));
    // do something with aSession object
    ...
}

@d3x0r
Copy link

d3x0r commented Dec 16, 2016

from here (v8 arraybuffer doc)
http://bespin.cz/~ondras/html/classv8_1_1ArrayBuffer.html

create arraybuffer with data (already populated)
memory has to be manually released later and is not garbage collected by default.

		Local<Object> arrayBuffer = ArrayBuffer::New( isolate, buf, fileSize );


		args.GetReturnValue().Set( arrayBuffer );

@jbdoster
Copy link

What about
Handle<Array> array = Handle<Array >::Cast(args[n])
for Arrays?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment