-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjectTranslator.cs
More file actions
1596 lines (1448 loc) · 56.1 KB
/
ObjectTranslator.cs
File metadata and controls
1596 lines (1448 loc) · 56.1 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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
namespace XLua
{
using System;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
class ReferenceEqualsComparer : IEqualityComparer<object>
{
public new bool Equals(object o1, object o2)
{
return object.ReferenceEquals(o1, o2);
}
public int GetHashCode(object obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
#pragma warning disable 414
public class MonoPInvokeCallbackAttribute : System.Attribute
{
private Type type;
public MonoPInvokeCallbackAttribute(Type t) { type = t; }
}
#pragma warning restore 414
public enum LuaTypes
{
LUA_TNONE = -1,
LUA_TNIL = 0,
LUA_TNUMBER = 3,
LUA_TSTRING = 4,
LUA_TBOOLEAN = 1,
LUA_TTABLE = 5,
LUA_TFUNCTION = 6,
LUA_TUSERDATA = 7,
LUA_TTHREAD = 8,
LUA_TLIGHTUSERDATA = 2
}
public enum LuaGCOptions
{
LUA_GCSTOP = 0,
LUA_GCRESTART = 1,
LUA_GCCOLLECT = 2,
LUA_GCCOUNT = 3,
LUA_GCCOUNTB = 4,
LUA_GCSTEP = 5,
LUA_GCSETPAUSE = 6,
LUA_GCSETSTEPMUL = 7,
}
public enum LuaThreadStatus
{
LUA_RESUME_ERROR = -1,
LUA_OK = 0,
LUA_YIELD = 1,
LUA_ERRRUN = 2,
LUA_ERRSYNTAX = 3,
LUA_ERRMEM = 4,
LUA_ERRERR = 5,
}
sealed class LuaIndexes
{
public static int LUA_REGISTRYINDEX
{
get
{
return InternalGlobals.LUA_REGISTRYINDEX;
}
set
{
InternalGlobals.LUA_REGISTRYINDEX = value;
}
}
}
#if GEN_CODE_MINIMIZE
public delegate int CSharpWrapper(IntPtr L, int top);
#endif
public partial class ObjectTranslator
{
internal MethodWrapsCache methodWrapsCache;
internal ObjectCheckers objectCheckers;
internal ObjectCasters objectCasters;
internal readonly ObjectPool objects = new ObjectPool();
internal readonly Dictionary<object, int> reverseMap = new Dictionary<object, int>(new ReferenceEqualsComparer());
internal LuaEnv luaEnv;
internal StaticLuaCallbacks metaFunctions;
internal List<Assembly> assemblies;
private LuaCSFunction importTypeFunction,loadAssemblyFunction, castFunction;
//延迟加载
private readonly Dictionary<Type, Action<RealStatePtr>> delayWrap = new Dictionary<Type, Action<RealStatePtr>>();
private readonly Dictionary<Type, Func<int, LuaEnv, LuaBase>> interfaceBridgeCreators = new Dictionary<Type, Func<int, LuaEnv, LuaBase>>();
//无法访问的类,比如声明成internal,可以用其接口、基类的生成代码来访问
private readonly Dictionary<Type, Type> aliasCfg = new Dictionary<Type, Type>();
public void DelayWrapLoader(Type type, Action<RealStatePtr> loader)
{
delayWrap[type] = loader;
}
public void AddInterfaceBridgeCreator(Type type, Func<int, LuaEnv, LuaBase> creator)
{
interfaceBridgeCreators.Add(type, creator);
}
Dictionary<Type, bool> loaded_types = new Dictionary<Type, bool>();
public bool TryDelayWrapLoader(RealStatePtr L, Type type)
{
if (loaded_types.ContainsKey(type)) return true;
loaded_types.Add(type, true);
LuaAPI.luaL_newmetatable(L, type.FullName); //先建一个metatable,因为加载过程可能会需要用到
LuaAPI.lua_pop(L, 1);
Action<RealStatePtr> loader;
int top = LuaAPI.lua_gettop(L);
if (delayWrap.TryGetValue(type, out loader))
{
delayWrap.Remove(type);
loader(L);
}
else
{
#if !GEN_CODE_MINIMIZE && !ENABLE_IL2CPP && (UNITY_EDITOR || XLUA_GENERAL) && !FORCE_REFLECTION
if (!DelegateBridge.Gen_Flag && !type.IsEnum() && !typeof(Delegate).IsAssignableFrom(type) && Utils.IsPublic(type))
{
Type wrap = ce.EmitTypeWrap(type);
MethodInfo method = wrap.GetMethod("__Register", BindingFlags.Static | BindingFlags.Public);
method.Invoke(null, new object[] { L });
}
else
{
Utils.ReflectionWrap(L, type);
}
#else
Utils.ReflectionWrap(L, type);
#endif
#if NOT_GEN_WARNING
#if !XLUA_GENERAL
UnityEngine.Debug.LogWarning(string.Format("{0} not gen, using reflection instead", type));
#else
System.Console.WriteLine(string.Format("Warning: {0} not gen, using reflection instead", type));
#endif
#endif
}
if (top != LuaAPI.lua_gettop(L))
{
throw new Exception("top change, before:" + top + ", after:" + LuaAPI.lua_gettop(L));
}
foreach (var nested_type in type.GetNestedTypes(BindingFlags.Public))
{
if (nested_type.IsGenericTypeDefinition())
{
continue;
}
TryDelayWrapLoader(L, nested_type);
}
return true;
}
public void Alias(Type type, string alias)
{
Type alias_type = FindType(alias);
if (alias_type == null)
{
throw new ArgumentException("Can not find " + alias);
}
aliasCfg[alias_type] = type;
}
public int cacheRef;
void addAssemblieByName(IEnumerable<Assembly> assemblies_usorted, string name)
{
foreach(var assemblie in assemblies_usorted)
{
if (assemblie.FullName.StartsWith(name) && !assemblies.Contains(assemblie))
{
assemblies.Add(assemblie);
break;
}
}
}
public ObjectTranslator(LuaEnv luaenv,RealStatePtr L)
{
#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR)
var dumb_field = typeof(ObjectTranslator).GetField("s_gen_reg_dumb_obj", BindingFlags.Static| BindingFlags.DeclaredOnly | BindingFlags.NonPublic);
if (dumb_field != null)
{
dumb_field.GetValue(null);
}
#endif
assemblies = new List<Assembly>();
#if UNITY_WSA && !UNITY_EDITOR
var assemblies_usorted = Utils.GetAssemblies();
#else
assemblies.Add(Assembly.GetExecutingAssembly());
var assemblies_usorted = AppDomain.CurrentDomain.GetAssemblies();
#endif
addAssemblieByName(assemblies_usorted, "mscorlib,");
addAssemblieByName(assemblies_usorted, "System,");
addAssemblieByName(assemblies_usorted, "System.Core,");
foreach (Assembly assembly in assemblies_usorted)
{
if (!assemblies.Contains(assembly))
{
assemblies.Add(assembly);
}
}
this.luaEnv=luaenv;
objectCasters = new ObjectCasters(this);
objectCheckers = new ObjectCheckers(this);
methodWrapsCache = new MethodWrapsCache(this, objectCheckers, objectCasters);
metaFunctions=new StaticLuaCallbacks();
importTypeFunction = new LuaCSFunction(StaticLuaCallbacks.ImportType);
loadAssemblyFunction = new LuaCSFunction(StaticLuaCallbacks.LoadAssembly);
castFunction = new LuaCSFunction(StaticLuaCallbacks.Cast);
LuaAPI.lua_newtable(L);
LuaAPI.lua_newtable(L);
LuaAPI.xlua_pushasciistring(L, "__mode");
LuaAPI.xlua_pushasciistring(L, "v");
LuaAPI.lua_rawset(L, -3);
LuaAPI.lua_setmetatable(L, -2);
cacheRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
initCSharpCallLua();
}
internal enum LOGLEVEL{
NO,
INFO,
WARN,
ERROR
}
Type delegate_birdge_type;
#if UNITY_EDITOR || XLUA_GENERAL
class CompareByArgRet : IEqualityComparer<MethodInfo>
{
public bool Equals(MethodInfo x, MethodInfo y)
{
return Utils.IsParamsMatch(x, y);
}
public int GetHashCode(MethodInfo method)
{
int hc = 0;
hc += method.ReturnType.GetHashCode();
foreach (var pi in method.GetParameters())
{
hc += pi.ParameterType.GetHashCode();
}
return hc;
}
}
#endif
void initCSharpCallLua()
{
delegate_birdge_type = typeof(DelegateBridge);
#if UNITY_EDITOR || XLUA_GENERAL
if (!DelegateBridge.Gen_Flag)
{
List<Type> cs_call_lua = new List<Type>();
foreach (var type in Utils.GetAllTypes())
{
if(type.IsDefined(typeof(CSharpCallLuaAttribute), false))
{
cs_call_lua.Add(type);
}
if (!type.IsAbstract || !type.IsSealed) continue;
var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
for (int i = 0; i < fields.Length; i++)
{
var field = fields[i];
if (field.IsDefined(typeof(CSharpCallLuaAttribute), false) && (typeof(IEnumerable<Type>)).IsAssignableFrom(field.FieldType))
{
cs_call_lua.AddRange(field.GetValue(null) as IEnumerable<Type>);
}
}
var props = type.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
for (int i = 0; i < props.Length; i++)
{
var prop = props[i];
if (prop.IsDefined(typeof(CSharpCallLuaAttribute), false) && (typeof(IEnumerable<Type>)).IsAssignableFrom(prop.PropertyType))
{
cs_call_lua.AddRange(prop.GetValue(null, null) as IEnumerable<Type>);
}
}
}
IEnumerable<IGrouping<MethodInfo, Type>> groups = (from type in cs_call_lua
where typeof(Delegate).IsAssignableFrom(type) && type != typeof(Delegate) && type != typeof(MulticastDelegate)
where !type.GetMethod("Invoke").GetParameters().Any(paramInfo => paramInfo.ParameterType.IsGenericParameter)
select type).GroupBy(t => t.GetMethod("Invoke"), new CompareByArgRet());
ce.SetGenInterfaces(cs_call_lua.Where(type=>type.IsInterface()).ToList());
delegate_birdge_type = ce.EmitDelegateImpl(groups);
}
#endif
}
#if UNITY_EDITOR || XLUA_GENERAL
CodeEmit ce = new CodeEmit();
#endif
Delegate getDelegate(DelegateBridgeBase bridge, Type delegateType)
{
Delegate ret = bridge.GetDelegateByType(delegateType);
if (ret != null)
{
return ret;
}
if (delegateType == typeof(Delegate) || delegateType == typeof(MulticastDelegate))
{
return null;
}
// get by parameters
MethodInfo delegateMethod = delegateType.GetMethod("Invoke");
var methods = bridge.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
for (int i = 0; i < methods.Length; i++)
{
if (!methods[i].IsConstructor && Utils.IsParamsMatch(delegateMethod, methods[i]))
{
#if !UNITY_WSA || UNITY_EDITOR
return Delegate.CreateDelegate(delegateType, bridge, methods[i]);
#else
return methods[i].CreateDelegate(delegateType, bridge);
#endif
}
}
throw new InvalidCastException("This type must add to CSharpCallLua: " + delegateType);
}
Dictionary<int, WeakReference> delegate_bridges = new Dictionary<int, WeakReference>();
public object CreateDelegateBridge(RealStatePtr L, Type delegateType, int idx)
{
LuaAPI.lua_pushvalue(L, idx);
LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
if (!LuaAPI.lua_isnil(L, -1))
{
int referenced = LuaAPI.xlua_tointeger(L, -1);
LuaAPI.lua_pop(L, 1);
if (delegate_bridges[referenced].IsAlive)
{
if (delegateType == null)
{
return delegate_bridges[referenced].Target;
}
DelegateBridgeBase exist_bridge = delegate_bridges[referenced].Target as DelegateBridgeBase;
Delegate exist_delegate;
if (exist_bridge.TryGetDelegate(delegateType, out exist_delegate))
{
return exist_delegate;
}
else
{
exist_delegate = getDelegate(exist_bridge, delegateType);
exist_bridge.AddDelegate(delegateType, exist_delegate);
return exist_delegate;
}
}
}
else
{
LuaAPI.lua_pop(L, 1);
}
LuaAPI.lua_pushvalue(L, idx);
int reference = LuaAPI.luaL_ref(L);
LuaAPI.lua_pushvalue(L, idx);
LuaAPI.lua_pushnumber(L, reference);
LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX);
DelegateBridgeBase bridge;
try
{
#if UNITY_EDITOR || XLUA_GENERAL
if (!DelegateBridge.Gen_Flag)
{
bridge = Activator.CreateInstance(delegate_birdge_type, new object[] { reference, luaEnv }) as DelegateBridgeBase;
}
else
#endif
{
bridge = new DelegateBridge(reference, luaEnv);
}
}
catch(Exception e)
{
LuaAPI.lua_pushvalue(L, idx);
LuaAPI.lua_pushnil(L);
LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.lua_pushnil(L);
LuaAPI.xlua_rawseti(L, LuaIndexes.LUA_REGISTRYINDEX, reference);
throw e;
}
if (delegateType == null)
{
delegate_bridges[reference] = new WeakReference(bridge);
return bridge;
}
try {
var ret = getDelegate(bridge, delegateType);
bridge.AddDelegate(delegateType, ret);
delegate_bridges[reference] = new WeakReference(bridge);
return ret;
}
catch(Exception e)
{
bridge.Dispose();
throw e;
}
}
public bool AllDelegateBridgeReleased()
{
foreach (var kv in delegate_bridges)
{
if (kv.Value.IsAlive)
{
return false;
}
}
return true;
}
public void ReleaseLuaBase(RealStatePtr L, int reference, bool is_delegate)
{
if(is_delegate)
{
LuaAPI.xlua_rawgeti(L, LuaIndexes.LUA_REGISTRYINDEX, reference);
if (LuaAPI.lua_isnil(L, -1))
{
LuaAPI.lua_pop(L, 1);
}
else
{
LuaAPI.lua_pushvalue(L, -1);
LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
if (LuaAPI.lua_type(L, -1) == LuaTypes.LUA_TNUMBER && LuaAPI.xlua_tointeger(L, -1) == reference) //
{
//UnityEngine.Debug.LogWarning("release delegate ref = " + luaReference);
LuaAPI.lua_pop(L, 1);// pop LUA_REGISTRYINDEX[func]
LuaAPI.lua_pushnil(L);
LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); // LUA_REGISTRYINDEX[func] = nil
}
else //another Delegate ref the function before the GC tick
{
LuaAPI.lua_pop(L, 2); // pop LUA_REGISTRYINDEX[func] & func
}
}
LuaAPI.lua_unref(L, reference);
delegate_bridges.Remove(reference);
}
else
{
LuaAPI.lua_unref(L, reference);
}
}
public object CreateInterfaceBridge(RealStatePtr L, Type interfaceType, int idx)
{
Func<int, LuaEnv, LuaBase> creator;
if (!interfaceBridgeCreators.TryGetValue(interfaceType, out creator))
{
#if UNITY_EDITOR || XLUA_GENERAL
var bridgeType = ce.EmitInterfaceImpl(interfaceType);
creator = (int reference, LuaEnv luaenv) =>
{
return Activator.CreateInstance(bridgeType, new object[] { reference, luaEnv }) as LuaBase;
};
interfaceBridgeCreators.Add(interfaceType, creator);
#else
throw new InvalidCastException("This type must add to CSharpCallLua: " + interfaceType);
#endif
}
LuaAPI.lua_pushvalue(L, idx);
return creator(LuaAPI.luaL_ref(L), luaEnv);
}
int common_array_meta = -1;
public void CreateArrayMetatable(RealStatePtr L)
{
Utils.BeginObjectRegister(null, L, this, 0, 0, 1, 0, common_array_meta);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "Length", StaticLuaCallbacks.ArrayLength);
Utils.EndObjectRegister(null, L, this, null, null,
typeof(System.Array), StaticLuaCallbacks.ArrayIndexer, StaticLuaCallbacks.ArrayNewIndexer);
}
int common_delegate_meta = -1;
public void CreateDelegateMetatable(RealStatePtr L)
{
Utils.BeginObjectRegister(null, L, this, 3, 0, 0, 0, common_delegate_meta);
Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__call", StaticLuaCallbacks.DelegateCall);
Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__add", StaticLuaCallbacks.DelegateCombine);
Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__sub", StaticLuaCallbacks.DelegateRemove);
Utils.EndObjectRegister(null, L, this, null, null,
typeof(System.MulticastDelegate), null, null);
}
int enumerable_pairs_func = -1;
internal void CreateEnumerablePairs(RealStatePtr L)
{
LuaFunction func = luaEnv.DoString(@"
return function(obj)
local isKeyValuePair
local function lua_iter(cs_iter, k)
if cs_iter:MoveNext() then
local current = cs_iter.Current
if isKeyValuePair == nil then
if type(current) == 'userdata' then
local t = current:GetType()
isKeyValuePair = t.Name == 'KeyValuePair`2' and t.Namespace == 'System.Collections.Generic'
else
isKeyValuePair = false
end
--print(current, isKeyValuePair)
end
if isKeyValuePair then
return current.Key, current.Value
else
return k + 1, current
end
end
end
return lua_iter, obj:GetEnumerator(), -1
end
")[0] as LuaFunction;
func.push(L);
enumerable_pairs_func = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
func.Dispose();
}
public void OpenLib(RealStatePtr L)
{
if (0 != LuaAPI.xlua_getglobal(L, "xlua"))
{
throw new Exception("call xlua_getglobal fail!" + LuaAPI.lua_tostring(L, -1));
}
LuaAPI.xlua_pushasciistring(L, "import_type");
LuaAPI.lua_pushstdcallcfunction(L,importTypeFunction);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "cast");
LuaAPI.lua_pushstdcallcfunction(L, castFunction);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "load_assembly");
LuaAPI.lua_pushstdcallcfunction(L,loadAssemblyFunction);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "access");
LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.XLuaAccess);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "private_accessible");
LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.XLuaPrivateAccessible);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "metatable_operation");
LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.XLuaMetatableOperation);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "tofunction");
LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.ToFunction);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "release");
LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.ReleaseCsObject);
LuaAPI.lua_rawset(L, -3);
LuaAPI.lua_pop(L, 1);
LuaAPI.lua_createtable(L, 1, 4); // 4 for __gc, __tostring, __index, __newindex
common_array_meta = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.lua_createtable(L, 1, 4); // 4 for __gc, __tostring, __index, __newindex
common_delegate_meta = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
}
internal void createFunctionMetatable(RealStatePtr L)
{
LuaAPI.lua_newtable(L);
LuaAPI.xlua_pushasciistring(L,"__gc");
LuaAPI.lua_pushstdcallcfunction(L,metaFunctions.GcMeta);
LuaAPI.lua_rawset(L,-3);
LuaAPI.lua_pushlightuserdata(L, LuaAPI.xlua_tag());
LuaAPI.lua_pushnumber(L, 1);
LuaAPI.lua_rawset(L, -3);
LuaAPI.lua_pushvalue(L, -1);
int type_id = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.lua_pushnumber(L, type_id);
LuaAPI.xlua_rawseti(L, -2, 1);
LuaAPI.lua_pop(L, 1);
typeIdMap.Add(typeof(LuaCSFunction), type_id);
}
internal Type FindType(string className, bool isQualifiedName = false)
{
foreach (Assembly assembly in assemblies)
{
Type klass = assembly.GetType(className);
if (klass!=null)
{
return klass;
}
}
int p1 = className.IndexOf('[');
if (p1 > 0 && !isQualifiedName)
{
string qualified_name = className.Substring(0, p1 + 1);
string[] generic_params = className.Substring(p1 + 1, className.Length - qualified_name.Length - 1).Split(',');
for(int i = 0; i < generic_params.Length; i++)
{
Type generic_param = FindType(generic_params[i].Trim());
if (generic_param == null)
{
return null;
}
if (i != 0 )
{
qualified_name += ", ";
}
qualified_name = qualified_name + "[" + generic_param.AssemblyQualifiedName + "]";
}
qualified_name += "]";
return FindType(qualified_name, true);
}
return null;
}
bool hasMethod(Type type, string methodName)
{
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
{
if (method.Name == methodName)
{
return true;
}
}
return false;
}
internal void collectObject(int obj_index_to_collect)
{
object o;
if (objects.TryGetValue(obj_index_to_collect, out o))
{
objects.Remove(obj_index_to_collect);
if (o != null)
{
int obj_index;
//lua gc是先把weak table移除后再调用__gc,这期间同一个对象可能再次push到lua,关联到新的index
bool is_enum = o.GetType().IsEnum();
if ((is_enum ? enumMap.TryGetValue(o, out obj_index) : reverseMap.TryGetValue(o, out obj_index))
&& obj_index == obj_index_to_collect)
{
if (is_enum)
{
enumMap.Remove(o);
}
else
{
reverseMap.Remove(o);
}
}
}
}
}
int addObject(object obj, bool is_valuetype, bool is_enum)
{
int index = objects.Add(obj);
if (is_enum)
{
enumMap[obj] = index;
}
else if (!is_valuetype)
{
reverseMap[obj] = index;
}
return index;
}
internal object GetObject(RealStatePtr L,int index)
{
return (objectCasters.GetCaster(typeof(object))(L, index, null));
}
public Type GetTypeOf(RealStatePtr L, int idx)
{
Type type = null;
int type_id = LuaAPI.xlua_gettypeid(L, idx);
if (type_id != -1)
{
typeMap.TryGetValue(type_id, out type);
}
return type;
}
public bool Assignable<T>(RealStatePtr L, int index)
{
return Assignable(L, index, typeof(T));
}
public bool Assignable(RealStatePtr L, int index, Type type)
{
if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) // 快路径
{
int udata = LuaAPI.xlua_tocsobj_safe(L, index);
object obj;
if (udata != -1 && objects.TryGetValue(udata, out obj))
{
RawObject rawObject = obj as RawObject;
if (rawObject != null)
{
obj = rawObject.Target;
}
return type.IsAssignableFrom(obj.GetType());
}
int type_id = LuaAPI.xlua_gettypeid(L, index);
Type type_of_struct;
if (type_id != -1 && typeMap.TryGetValue(type_id, out type_of_struct)) // is struct
{
return type.IsAssignableFrom(type_of_struct);
}
}
return objectCheckers.GetChecker(type)(L, index);
}
public object GetObject(RealStatePtr L, int index, Type type)
{
int udata = LuaAPI.xlua_tocsobj_safe(L, index);
if (udata != -1)
{
object obj = objects.Get(udata);
RawObject rawObject = obj as RawObject;
return rawObject == null ? obj : rawObject.Target;
}
else
{
if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA)
{
GetCSObject get;
int type_id = LuaAPI.xlua_gettypeid(L, index);
if (type_id != -1 && type_id == decimal_type_id)
{
decimal d;
Get(L, index, out d);
return d;
}
Type type_of_struct;
if (type_id != -1 && typeMap.TryGetValue(type_id, out type_of_struct) && type.IsAssignableFrom(type_of_struct) && custom_get_funcs.TryGetValue(type, out get))
{
return get(L, index);
}
}
return (objectCasters.GetCaster(type)(L, index, null));
}
}
public void Get<T>(RealStatePtr L, int index, out T v)
{
Func<RealStatePtr, int, T> get_func;
if (tryGetGetFuncByType(typeof(T), out get_func))
{
v = get_func(L, index);
}
else
{
v = (T)GetObject(L, index, typeof(T));
}
}
public void PushByType<T>(RealStatePtr L, T v)
{
Action<RealStatePtr, T> push_func;
if (tryGetPushFuncByType(typeof(T), out push_func))
{
push_func(L, v);
}
else
{
PushAny(L, v);
}
}
#if GENERIC_SHARING
public T GetByType<T>(RealStatePtr L, int index)
{
Func<RealStatePtr, int, T> get_func;
if (tryGetGetFuncByType(typeof(T), out get_func))
{
return get_func(L, index);
}
else
{
return (T)GetObject(L, index, typeof(T));
}
}
#endif
public T[] GetParams<T>(RealStatePtr L, int index)
{
T[] ret = new T[Math.Max(LuaAPI.lua_gettop(L) - index + 1, 0)];
for(int i = 0; i < ret.Length; i++)
{
Get(L, index + i, out ret[i]);
}
return ret;
}
public Array GetParams(RealStatePtr L, int index, Type type) //反射版本
{
Array ret = Array.CreateInstance(type, Math.Max(LuaAPI.lua_gettop(L) - index + 1, 0)); //这个函数,长度为0的话,返回null
for (int i = 0; i < ret.Length; i++)
{
ret.SetValue(GetObject(L, index + i, type), i);
}
return ret;
}
#if UNITY_EDITOR || XLUA_GENERAL
public void PushParams(RealStatePtr L, Array ary)
{
if (ary != null)
{
for (int i = 0; i < ary.Length; i++)
{
PushAny(L, ary.GetValue(i));
}
}
}
#endif
public T GetDelegate<T>(RealStatePtr L, int index) where T :class
{
if (LuaAPI.lua_isfunction(L, index))
{
return CreateDelegateBridge(L, typeof(T), index) as T;
}
else if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA)
{
return (T)SafeGetCSObj(L, index);
}
else
{
return null;
}
}
Dictionary<Type, int> typeIdMap = new Dictionary<Type, int>();
//only store the type id to type map for struct
Dictionary<int, Type> typeMap = new Dictionary<int, Type>();
public int GetTypeId(RealStatePtr L, Type type)
{
bool isFirst;
return getTypeId(L, type, out isFirst);
}
internal int getTypeId(RealStatePtr L, Type type, out bool is_first, LOGLEVEL log_level = LOGLEVEL.WARN)
{
int type_id;
is_first = false;
if (!typeIdMap.TryGetValue(type, out type_id)) // no reference
{
if (type.IsArray)
{
if (common_array_meta == -1) throw new Exception("Fatal Exception! Array Metatable not inited!");
return common_array_meta;
}
if (typeof(MulticastDelegate).IsAssignableFrom(type))
{
if (common_delegate_meta == -1) throw new Exception("Fatal Exception! Delegate Metatable not inited!");
return common_delegate_meta;
}
is_first = true;
Type alias_type = null;
aliasCfg.TryGetValue(type, out alias_type);
LuaAPI.luaL_getmetatable(L, alias_type == null ? type.FullName : alias_type.FullName);
if (LuaAPI.lua_isnil(L, -1)) //no meta yet, try to use reflection meta
{
LuaAPI.lua_pop(L, 1);
if (TryDelayWrapLoader(L, alias_type == null ? type : alias_type))
{
LuaAPI.luaL_getmetatable(L, alias_type == null ? type.FullName : alias_type.FullName);
}
else
{
throw new Exception("Fatal: can not load metatable of type:" + type);
}
}
//循环依赖,自身依赖自己的class,比如有个自身类型的静态readonly对象。
if (typeIdMap.TryGetValue(type, out type_id))
{
LuaAPI.lua_pop(L, 1);
}
else
{
if (type.IsEnum())
{
LuaAPI.xlua_pushasciistring(L, "__band");
LuaAPI.lua_pushstdcallcfunction(L, metaFunctions.EnumAndMeta);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "__bor");
LuaAPI.lua_pushstdcallcfunction(L, metaFunctions.EnumOrMeta);
LuaAPI.lua_rawset(L, -3);
}
if (typeof(IEnumerable).IsAssignableFrom(type))
{
LuaAPI.xlua_pushasciistring(L, "__pairs");
LuaAPI.lua_getref(L, enumerable_pairs_func);
LuaAPI.lua_rawset(L, -3);
}
LuaAPI.lua_pushvalue(L, -1);
type_id = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.lua_pushnumber(L, type_id);
LuaAPI.xlua_rawseti(L, -2, 1);
LuaAPI.lua_pop(L, 1);
if (type.IsValueType())
{
typeMap.Add(type_id, type);
}
typeIdMap.Add(type, type_id);
}
}
return type_id;
}
void pushPrimitive(RealStatePtr L, object o)
{
if (o is sbyte || o is byte || o is short || o is ushort ||
o is int)
{
int i = Convert.ToInt32(o);
LuaAPI.xlua_pushinteger(L, i);
}
else if (o is uint)
{
LuaAPI.xlua_pushuint(L, (uint)o);
}
else if (o is float || o is double)
{
double d = Convert.ToDouble(o);
LuaAPI.lua_pushnumber(L, d);
}
else if (o is IntPtr)
{