@@ -267,13 +267,58 @@ internal class GeneratorContext
267267 public readonly StringGenerator StrGen = new StringGenerator ( ) ;
268268 private readonly HashSet < string > UsedTypeNames = new HashSet < string > ( ) ;
269269 private readonly HashSet < string > UsedMethodNames = new HashSet < string > ( ) ;
270+ private readonly Dictionary < string , List < Tuple < string , bool > > > InitFldsMap = new Dictionary < string , List < Tuple < string , bool > > > ( ) ;
270271 private uint TypeIDCounter ;
271272
272273 public GeneratorContext ( TypeManager typeMgr )
273274 {
274275 TypeMgr = typeMgr ;
275276 }
276277
278+ public void AddStaticField ( string typeName , string sfldName , bool hasRef )
279+ {
280+ if ( ! InitFldsMap . TryGetValue ( typeName , out var nameSet ) )
281+ {
282+ nameSet = new List < Tuple < string , bool > > ( ) ;
283+ InitFldsMap . Add ( typeName , nameSet ) ;
284+ }
285+ nameSet . Add ( new Tuple < string , bool > ( sfldName , hasRef ) ) ;
286+ }
287+
288+ private CompileUnit GenInitUnit ( Dictionary < string , string > transMap )
289+ {
290+ CompileUnit unit = new CompileUnit ( ) ;
291+ unit . Name = "il2cppInit" ;
292+
293+ CodePrinter prtGC = new CodePrinter ( ) ;
294+ CodePrinter prtInit = new CodePrinter ( ) ;
295+ foreach ( var kv in InitFldsMap )
296+ {
297+ unit . ImplDepends . Add ( transMap [ kv . Key ] ) ;
298+
299+ foreach ( var item in kv . Value )
300+ {
301+ if ( item . Item2 )
302+ prtGC . AppendFormatLine ( "IL2CPP_ADD_ROOT({0});" , item . Item1 ) ;
303+ prtInit . AppendFormatLine ( "{0} = {{}};" , item . Item1 ) ;
304+ }
305+ }
306+
307+ prtGC . AppendLine ( "il2cpp_CommitRoots();" ) ;
308+
309+ CodePrinter prtFunc = new CodePrinter ( ) ;
310+ prtFunc . AppendLine ( "void il2cpp_InitVariables()\n {" ) ;
311+ ++ prtFunc . Indents ;
312+ prtFunc . Append ( prtGC . ToString ( ) ) ;
313+ prtFunc . Append ( prtInit . ToString ( ) ) ;
314+ -- prtFunc . Indents ;
315+ prtFunc . AppendLine ( "}" ) ;
316+
317+ unit . ImplCode = prtFunc . ToString ( ) ;
318+
319+ return unit ;
320+ }
321+
277322 public GenerateResult Generate ( )
278323 {
279324 var unitMap = new Dictionary < string , CompileUnit > ( ) ;
@@ -294,6 +339,10 @@ public GenerateResult Generate()
294339 if ( strTyX != null )
295340 StrGen . Generate ( unitMap , GetTypeID ( strTyX ) ) ;
296341
342+ // 生成初始化单元
343+ var unitInit = GenInitUnit ( transMap ) ;
344+ unitMap [ unitInit . Name ] = unitInit ;
345+
297346 return new GenerateResult ( this , unitMap . Values . ToList ( ) , transMap ) ;
298347 }
299348
0 commit comments