This repository has been archived by the owner on Feb 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
object1.cc
74 lines (58 loc) · 2.05 KB
/
object1.cc
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
#include <v8.h>
#include <iostream>
#include <string>
using namespace v8;
using namespace std;
class Point {
public:
Point (int x, int y)
:x (x), y (y)
{
}
int x, y;
};
Handle<Value> XGetter (Local<String> property, const AccessorInfo& info) {
Handle<Object> obj = info.This ();
Point& point = *static_cast<Point*> (
Local<External>::Cast(obj->GetInternalField(0))->Value ());
return Integer::New (point.x);
}
void XSetter (Local<String> property, Local<Value> value,
const AccessorInfo& info) {
Handle<Object> obj = info.This ();
Point& point = *static_cast<Point*> (
Local<External>::Cast(obj->GetInternalField(0))->Value ());
point.x = value->Int32Value();
}
Handle<Value> YGetter (Local<String> property, const AccessorInfo& info) {
Handle<Object> obj = info.This ();
Point& point = *static_cast<Point*> (
Local<External>::Cast(obj->GetInternalField(0))->Value ());
return Integer::New (point.y);
}
void YSetter (Local<String> property, Local<Value> value,
const AccessorInfo& info) {
Handle<Object> obj = info.This ();
Point& point = *static_cast<Point*> (
Local<External>::Cast(obj->GetInternalField(0))->Value ());
point.y = value->Int32Value();
}
int main(int argc, char *argv[])
{
HandleScope handle_scope;
Handle<Context> context = Context::New();
Context::Scope context_scope(context);
// 建造ObjectTemplate
Handle<ObjectTemplate> obj_tpl = ObjectTemplate::New ();
obj_tpl->SetInternalFieldCount (1);
// 建立Object,并与C++对象绑定
Point point (10, 10);
Handle<Object> obj = obj_tpl->NewInstance ();
obj->SetInternalField (0, External::New (&point));
obj->SetAccessor(String::New("x"), XGetter, XSetter);
obj->SetAccessor(String::New("y"), YGetter, YSetter);
// 打印结果
cout << *String::AsciiValue (obj->Get (String::New ("x"))) << endl;
cout << *String::AsciiValue (obj->Get (String::New ("y"))) << endl;
return 0;
}