@@ -90,14 +90,42 @@ inline void check_class_id(const char *a, const char *b) {
90
90
#define CHECK_CLASS_ID (env, PTR )
91
91
#endif
92
92
93
- // /* Delete a native C++ object when the Garbage Collector reclaims its
94
- // JavaScript handle.
95
- // */
96
- // template<typename PTR>
97
- // void onGcReclaim(const WeakCallbackData<Object, PTR> data) {
98
- // PTR ptr = data.GetParameter();
99
- // if(ptr) delete ptr;
100
- // }
93
+ /* Delete a native C++ object when the Garbage Collector reclaims its
94
+ JavaScript handle.
95
+ The GcReclaimer holds the pointer to be deleted, its classname for
96
+ debugging output, and the weak JS reference (which should be Reset).
97
+ */
98
+ template <typename CPP_OBJECT> class GcReclaimer ; // forward declaration
99
+
100
+ template <typename CPP_OBJECT>
101
+ void onGcReclaim (const WeakCallbackData<Value, GcReclaimer<CPP_OBJECT> > & data) {
102
+ GcReclaimer<CPP_OBJECT> * reclaimer = data.GetParameter ();
103
+ reclaimer->reclaim ();
104
+ delete reclaimer;
105
+ }
106
+
107
+ template <typename CPP_OBJECT> class GcReclaimer {
108
+ public:
109
+ GcReclaimer (const char * cls, CPP_OBJECT * p) : classname(cls), ptr(p) { }
110
+
111
+ void SetWeakReference (Isolate *isolate, Handle<Value> obj) {
112
+ notifier.Reset (isolate, obj);
113
+ notifier.MarkIndependent ();
114
+ notifier.SetWeak (this , onGcReclaim<CPP_OBJECT>);
115
+ }
116
+
117
+ void reclaim () {
118
+ delete ptr;
119
+ DEBUG_PRINT_DETAIL (" GC Reclaim %s %p" , classname, ptr);
120
+ notifier.Reset ();
121
+ }
122
+
123
+ private:
124
+ const char * classname;
125
+ CPP_OBJECT * ptr;
126
+ Persistent<Value> notifier;
127
+ };
128
+
101
129
102
130
/* ****************************************************************
103
131
An Envelope is a simple structure providing some safety
@@ -190,14 +218,11 @@ class Envelope {
190
218
(if you hold a const pointer to something, you probably don't own its
191
219
memory allocation).
192
220
******************************************************************/
193
- template <typename PTR>
194
- void freeFromGC (PTR ptr, Handle<Value> obj) {
221
+ template <typename P>
222
+ void freeFromGC (P * ptr, Handle<Value> obj) {
195
223
if (ptr) {
196
- Persistent<Object> notifier;
197
- notifier.Reset (isolate, obj->ToObject ());
198
- notifier.MarkIndependent ();
199
- // TODO: Figure this out
200
- // notifier.SetWeak((void *) ptr, onGcReclaim<PTR>);
224
+ GcReclaimer<P> * reclaimer = new GcReclaimer<P>(classname, ptr);
225
+ reclaimer->SetWeakReference (isolate, obj);
201
226
}
202
227
}
203
228
};
0 commit comments