forked from kkaefer/node-cpp-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodulename.cpp
More file actions
76 lines (47 loc) · 1.84 KB
/
modulename.cpp
File metadata and controls
76 lines (47 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <node.h>
#include "modulename.hpp"
using namespace v8;
Persistent<FunctionTemplate> MyObject::constructor;
void MyObject::Init(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
Local<String> name = String::NewSymbol("MyObject");
constructor = Persistent<FunctionTemplate>::New(tpl);
// ObjectWrap uses the first internal field to store the wrapped pointer.
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(name);
// Add all prototype methods, getters and setters here.
NODE_SET_PROTOTYPE_METHOD(constructor, "value", Value);
// This has to be last, otherwise the properties won't show up on the
// object in JavaScript.
target->Set(name, constructor->GetFunction());
}
MyObject::MyObject(int val)
: ObjectWrap(),
value_(val) {}
Handle<Value> MyObject::New(const Arguments& args) {
HandleScope scope;
if (!args.IsConstructCall()) {
return ThrowException(Exception::TypeError(
String::New("Use the new operator to create instances of this object."))
);
}
if (args.Length() < 1) {
return ThrowException(Exception::TypeError(
String::New("First argument must be a number")));
}
// Creates a new instance object of this type and wraps it.
MyObject* obj = new MyObject(args[0]->ToInteger()->Value());
obj->Wrap(args.This());
return args.This();
}
Handle<Value> MyObject::Value(const Arguments& args) {
HandleScope scope;
// Retrieves the pointer to the wrapped object instance.
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
return scope.Close(Integer::New(obj->value_));
}
void RegisterModule(Handle<Object> target) {
MyObject::Init(target);
}
NODE_MODULE(modulename, RegisterModule);