Skip to content

Instantly share code, notes, and snippets.

@tmpvar
Last active May 27, 2018 11:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmpvar/5414849 to your computer and use it in GitHub Desktop.
Save tmpvar/5414849 to your computer and use it in GitHub Desktop.
Basic usage of v8::External in a node addon
#include <node.h>
#include <v8.h>
using namespace v8;
using namespace node;
struct Obj {
int x;
};
Handle<Value> CreateThing(const Arguments& args) {
HandleScope scope;
Obj *o = new Obj;
o->x = 10;
return scope.Close(External::Wrap(o));
}
Handle<Value> UseThing(const Arguments& args) {
HandleScope scope;
Obj *o = reinterpret_cast<Obj *>(External::Unwrap(args[0]));
return scope.Close(Number::New(o->x));
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("createThing"),
FunctionTemplate::New(CreateThing)->GetFunction());
exports->Set(String::NewSymbol("useThing"),
FunctionTemplate::New(UseThing)->GetFunction());
}
NODE_MODULE(external, init)
/*
JS:
var val = binding.createThing();
console.log(binding.useThing(val)); // 10
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment