Last active
May 27, 2018 11:27
-
-
Save tmpvar/5414849 to your computer and use it in GitHub Desktop.
Basic usage of v8::External in a node addon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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