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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
|
#ifndef __LUA_BIND_CLASS_H__
#define __LUA_BIND_CLASS_H__
#include "LuaBindConfig.h"
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include "LuaBindRef.h"
#include "LuaBindMemberRef.h"
#include "LuaBindCFunctions.h"
#include "LuaBindWatchDog.h"
#include "LuaBindUtility.h"
#include "LuaBindHelper.h"
namespace LuaBind
{
class VM;
#define CLASS_NONE_ID (-1)
extern UIDGenerator gClassIDGenerator;
// 虚基类,为了实现多态。需要访问下面这些接口的外部基类需要虚继承此类,之后再派生链中就会
// 调用对应实体的方法。注意继承此类时不能实现下面的方法,实现在NativeClass中,实现会
// 导致二义性。
//
// 依据Effective C++条款40,如果在必须使用virtual base基类情况下,应该尽可能避免向其中放
// 置数据成员,规避数据成员初始化造成的一些隐性问题。依据这一点,vpb基类更加接近C#和Java中
// 的Interface。所以,在这里把类用I开头标识这是一个接口。
class Object
{
public:
Object() {};
virtual ~Object() {};
// 成员引用管理,在实例的ref table里。设置、取、清除。
virtual bool PushMemberRef(State& state, int refID) = 0;
virtual bool PushUserdata(State& state) = 0;
virtual bool PushRefTable(State& state) = 0;
// 被NativeClass实现。保持和释放native资源。
virtual void Retain() = 0;
virtual void Release() = 0;
};
// 需要暴露给lua的native class需要继承此类。通过lua管理的实例要确保引用计数的正确性,在多个线程中需要确
// 定不会误释放。
template<class TYPE, class BASE = Object>
class NativeClass : public BASE
{
public:
enum NativeClassTableIndex { kRefTable = 1, kClassTable = 2 };
// 将userdata作为key,在ref table里对userdata添加一个引用,以维持userdata的生命周期。
// 相比较member ref,这个用在实体会被多次被不同其他实体引用的情况,并频繁销毁这些实体,
// 避免lua频繁的调用gc检测。
template<class DATATYPE> void Retain(State& state, DATATYPE* userdata);
// 对userdata减少一个引用在ref table里,以尝试回收userdata。
template<class DATATYPE> void Release(State& state, DATATYPE* userdata);
// 将userdata push到栈顶,如果没有初始化mUserdata,初始化设置好元表并把初始化好的
// userdata留在栈顶。并添加一个引用。这是一个将native对象所有权移交给lua控制的方法。
bool PushUserdata(State& state) override;
bool PushMemberRef(State& state, int refID) override;
bool PushRefTable(State& state) override;
// WatchDog添加一个native引用。luaVM引用不会提供外部接口。继承此类的派生类不能直接使用
// delete方法,应该使用Release释放。一般情况下这个操作由虚拟机__gc进行,但是允许用户
// 程序在native中隔绝虚拟机情况下释放,这种情况下要使用Release。
//
// 这两个函数是native接口。
void Retain() override final;
void Release() override final;
#if LUA_BIND_PROFILER
// 对堆上创建的实例进行delete保险检查
static void operator delete(void* pdead, size_t size);
#endif
protected:
// 延后绑定VM
NativeClass();
// 需要指明对象所属的虚拟机
NativeClass(LuaBind::VM* vm);
virtual ~NativeClass();
LuaBind::VM* GetVM() { return mOwner; }
// 成员引用管理,在实例的ref table里。设置、取、清除
void SetMemberRef(State& state, MemberRef& memRef, int idx);
bool PushMemberRef(State& state, MemberRef& memRef);
void ClearMemberRef(State& state, MemberRef& memRef);
// 调用回调函数
void InvokeLuaCallback(LuaBind::MemberRef script, cc8* method);
private:
friend class State;
static void RegisterClassShared(State& state);
static void SetClassTableRef(State& state, int idx);
static void PushClassTable(State& state);
// 创建userdata,绑定实例到state。
void BindToLua(State& state);
// 延后绑定VM,在BindToLua中设置
void LateBindVM(VM* vm);
//------------------------------------------------------------------------------//
// 公共内容
static int __tostring (lua_State*);
static int _GetClass (lua_State*);
static int _GetClassName (lua_State*);
// 工厂类相关
static int __gc (lua_State*);
//--------------------------------------------------------------------------------//
// 类型的全局UID,在不同的虚拟机中相同
static int sClassID;
// 所属的虚拟机
LuaBind::VM* mOwner;
// 通过userdata可以拿到:
// 1: ref table
// 2: class table
WeakRef mUserdata;
// 通过后才能删除
WatchDog mWatchDog;
#if LUA_BIND_PROFILER
// 托管此对象的虚拟机
std::unordered_set<VM*> mRefVMs;
// 保险,此类的派生类不能在外部使用delete直接删除,而应该使用Release
bool mSafer;
#endif
};
//--------------------------------------------------------------------------------//
template<class TYPE, class BASE>
int NativeClass<TYPE, BASE>::sClassID = CLASS_NONE_ID;
// 对不同类型,通过调用GetLuaClassName获得类型名,如果是派生类,GetClassName会被覆盖,指向luax_c_getupvalue。
template<class TYPE, class BASE>
int NativeClass<TYPE, BASE>::_GetClassName(lua_State* L)
{
LUA_BIND_SETUP(L, "*");
cc8* type = TYPE::GetNativeClassName();
state.Push(type);
return 1;
}
//--------------------------------------------------------------------------------//
// 注册工厂和单例共有的类成员
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::RegisterClassShared(State& state)
{
luaL_Reg regTable[] = {
{ "GetClass", _GetClass },
{ "GetClassName", _GetClassName },
{ NULL, NULL }
};
state.RegisterMethods(regTable);
}
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::SetClassTableRef(State& state, int idx)
{
if (sClassID == CLASS_NONE_ID)
sClassID = gClassIDGenerator.GetID();
LuaBind::VM* vm = state.GetVM();
vm->RegisterNativeClass(state, sClassID, idx);
}
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::LateBindVM(VM* vm)
{
mOwner = vm;
}
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::PushClassTable(State& state)
{
LuaBind::VM* vm = state.GetVM();
vm->PushClassTable(state, sClassID);
}
template<class TYPE, class BASE>
NativeClass<TYPE, BASE>::NativeClass()
: mWatchDog()
, mUserdata(NULL)
, mOwner(NULL)
#if LUA_BIND_PROFILER
, mSafer(false)
#endif
{
}
template<class TYPE, class BASE>
NativeClass<TYPE, BASE>::NativeClass(LuaBind::VM* vm)
: mWatchDog()
, mUserdata(vm)
, mOwner(vm)
#if LUA_BIND_PROFILER
, mSafer(false)
#endif
{
}
template<class TYPE, class BASE>
NativeClass<TYPE, BASE>::~NativeClass()
{
}
#if LUA_BIND_PROFILER
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::operator delete(void* pdead, size_t size)
{
if (pdead == nullptr)
return;
// 堆上创建的实例必须使用Release释放。
TYPE* p = static_cast<TYPE*>(pdead);
assert(p->mSafer);
::operator delete(pdead, size);
}
#endif
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::Retain()
{
++mWatchDog.mNativeRef;
}
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::Release()
{
if (mWatchDog.mNativeRef > 0)
--mWatchDog.mNativeRef;
if (mWatchDog)
{
#if LUA_BIND_PROFILER
mSafer = true;
#endif
delete this;
}
}
template<class TYPE, class BASE>
template<typename U>
void NativeClass<TYPE, BASE>::Retain(State& state, U* userdata)
{
if (PushRefTable(state))
{
if (userdata->PushUserdata(state))
{
lua_pushvalue(state, -1); // copy the userdata
lua_gettable(state, -3); // get the count (or nil)
u32 count = state.GetValue<u32>(-1, 0); // get the count (or 0)
lua_pop(state, 1); // pop the old count
lua_pushnumber(state, count + 1); // push the new count
lua_settable(state, -3); // save it in the table: reftable[userdata] = count
}
}
}
template<class TYPE, class BASE>
template<typename U>
void NativeClass<TYPE, BASE>::Release(State& state, U* userdata)
{
if (PushRefTable(state))
{
if (userdata->PushUserdata(state))
{
lua_pushvalue(state, -1); // copy the userdata
lua_gettable(state, -3); // get the count (or nil)
u32 count = state.GetValue<u32>(-1, 0); // get the count (or 0)
lua_pop(state, 1); // pop the old count
// no such reference
if (count == 0)
{
state.Pop(2); // userdata, reftable
return; // nothing to do
}
if (count > 1) {
lua_pushnumber(state, count - 1); // push the new count
}
else {
lua_pushnil(state); // maybe cause gc
}
lua_settable(state, -3); // save it in the table
state.Pop(1); // reftable
return;
}
state.Pop(2); // nil, reftable
return;
}
}
template<class TYPE, class BASE>
bool NativeClass<TYPE, BASE>::PushUserdata(State& state)
{
if (!mUserdata) // 第一次创建
{
BindToLua(state);
return true;
}
return mUserdata.PushRef(state);
}
template<class TYPE, class BASE>
bool NativeClass<TYPE, BASE>::PushRefTable(State& state)
{
if (this->PushUserdata(state))
{
if (lua_getmetatable(state, -1)) // RefTable
{
lua_replace(state, -2);
return true;
}
}
return false;
}
// 创建userdata,并以此添加ref table,member table和class table。
// ref table 是kv强引用table,保存对其他GCObject的引用
// member table 保存lua创建的实例的成员
// class table 所有本类型的实例共有的函数表
//
// BindToLua只会在第一次注册给Lua虚拟机时调用。
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::BindToLua(State& state)
{
assert(!mUserdata);
if (mOwner == NULL)
{
LateBindVM(state.GetVM());
}
// 创建userdata并留在栈顶,注意地址要转换为TYPE*,直接用this可能会导致多重继承的类丧失多态。
// 如果直接传this进去,在多重继承情况下,是拿不到另一头的虚函数表的。所以这里需要将this
// 转换为整个对象的低地址,这样可以拿到另一个基类的虚函数表,通过另一个基类实现多态。
TYPE* p = static_cast<TYPE*>(this);
state.PushPtrUserdata(p);
lua_newtable(state); // ref table,无法在lua处访问,用来管理C对象的生命周期
PushClassTable(state); // class table
// stack:
// -1 class table
// -2 ref table
// -3 userdata
int clsTable = state.GetTop();
int refTable = clsTable - 1;
// ref table 注册 __tostring 和 __gc
lua_pushcfunction(state, __tostring);
lua_setfield(state, refTable, "__tostring");
lua_pushcfunction(state, __gc);
lua_setfield(state, refTable, "__gc");
// ref table 的 __index 和 __newindex 设为 member table
lua_pushvalue(state, clsTable);
lua_setfield(state, refTable, "__index");
lua_pushvalue(state, clsTable);
lua_setfield(state, refTable, "__newindex");
// 设置元表 userdata -> refTable -> classTable
lua_setmetatable(state, -2); // class is metatable of ref
lua_setmetatable(state, -2); // ref is metatable of userdata
// 设置一个userdata的弱引用,方便通过PushLuaUserdata方法返回lua对象
mUserdata.SetRef(state, -1);
assert(mUserdata);
// 增加一个虚拟机引用,在GC时-1
++mWatchDog.mVMRef;
#if LUA_BIND_PROFILER
mRefVMs.insert(state.GetVM());
#endif
}
// 成员引用管理
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::SetMemberRef(State& state, MemberRef& outRef, int idx)
{
ClearMemberRef(state, outRef);
if (!lua_isnil(state, idx))
{
idx = state.AbsIndex(idx);
if (PushRefTable(state)) // RefTable
{
lua_pushvalue(state, idx);
outRef.refID = luaL_ref(state, -2);
state.Pop(); // ref table
}
}
}
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::InvokeLuaCallback(LuaBind::MemberRef script, cc8* method)
{
if (!script)
return;
LuaBind::State state = GetVM()->GetCurThread();
int top = state.GetTop();
PushMemberRef(state, script);
state.GetField(-1, method);
PushMemberRef(state, script);
state.Call(1, 0, onErrorOccured);
state.SetTop(top);
}
template<class TYPE, class BASE>
bool NativeClass<TYPE, BASE>::PushMemberRef(State& state, MemberRef& memRef)
{
if (memRef)
{
if (PushRefTable(state)) // RefTable
{
lua_rawgeti(state, -1, memRef.refID);
lua_replace(state, -2); // ref table
if (lua_isnil(state, -1))
goto failed;
return true;
}
}
lua_pushnil(state);
failed:
memRef.refID = LUA_NOREF;
return false;
}
template<class TYPE, class BASE>
bool NativeClass<TYPE, BASE>::PushMemberRef(State& state, int refID)
{
if (PushRefTable(state)) // RefTable
{
lua_rawgeti(state, -1, refID);
lua_replace(state, -2); // ref table
if (lua_isnil(state, -1))
goto failed;
return true;
}
lua_pushnil(state);
failed:
return false;
}
template<class TYPE, class BASE>
void NativeClass<TYPE, BASE>::ClearMemberRef(State& state, MemberRef& memRef)
{
if (memRef)
{
if (PushRefTable(state)) // RefTable
{
luaL_unref(state, -1, memRef.refID);
state.Pop(); // ref table
}
memRef.refID = LUA_NOREF;
}
}
//--------------------------------------------------------------------------------//
//
// 释放工厂创建的实例
//
template<class TYPE, class BASE>
int NativeClass<TYPE, BASE>::__gc(lua_State* L)
{
LUA_BIND_STATE(L);
TYPE* self = state.GetUserdata<TYPE>(1);
assert(self);
#if LUA_BIND_PROFILER
std::cout << ": GC<" << TYPE::GetNativeClassName() << ">\n";
#endif
if (self->mWatchDog.mVMRef > 0)
--self->mWatchDog.mVMRef;
self->Release();
return 0;
}
//
// 输出格式如下:
// 地址 类名
//
template<class TYPE, class BASE>
int NativeClass<TYPE, BASE>::__tostring(lua_State* L)
{
// params:
// 1: userdata
LUA_BIND_STATE(L);
TYPE* self = state.GetUserdata<TYPE>(1);
if (self)
{
cc8* classname = "";
lua_getfield(state, 1, "GetClassName");
if (state.IsType(-1, LUA_TFUNCTION))
{
lua_pushvalue(L, 1); // userdata
state.Call(1, 1, onErrorOccured); // 派生类的GetClassName函数
classname = state.GetValue<cc8*>(-1, "");
}
else
{
classname = TYPE::GetNativeClassName();
}
lua_pushfstring(L, "%s: %p", classname, self);
return 1;
}
return 0;
}
template<class TYPE, class BASE>
int NativeClass<TYPE, BASE>::_GetClass(lua_State* L)
{
LUA_BIND_STATE(L);
state.GetVM()->PushClassTable(state, sClassID);
return 1;
}
}
#endif
|