From a084026d19350d95322464ab8cd600d5906eae6a Mon Sep 17 00:00:00 2001 From: Jeremy Pritts <49847914+ds5678@users.noreply.github.com> Date: Sat, 19 Oct 2024 12:16:52 -0700 Subject: [PATCH] Support resolving a field's declaring type (#347) --- LibCpp2IL/Reflection/LibCpp2IlReflection.cs | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/LibCpp2IL/Reflection/LibCpp2IlReflection.cs b/LibCpp2IL/Reflection/LibCpp2IlReflection.cs index cb754ab1..1b8110af 100644 --- a/LibCpp2IL/Reflection/LibCpp2IlReflection.cs +++ b/LibCpp2IL/Reflection/LibCpp2IlReflection.cs @@ -17,6 +17,8 @@ public static class LibCpp2IlReflection private static readonly Dictionary FieldIndices = new(); private static readonly Dictionary PropertyIndices = new(); + private static readonly Dictionary FieldDeclaringTypes = new(); + private static readonly Dictionary PrimitiveTypeCache = new(); public static readonly Dictionary PrimitiveTypeDefinitions = new(); private static readonly Dictionary Il2CppTypeCache = new(); @@ -32,6 +34,7 @@ internal static void ResetCaches() MethodIndices.Clear(); FieldIndices.Clear(); PropertyIndices.Clear(); + FieldDeclaringTypes.Clear(); PrimitiveTypeCache.Clear(); PrimitiveTypeDefinitions.Clear(); Il2CppTypeCache.Clear(); @@ -197,6 +200,30 @@ public static int GetPropertyIndexFromProperty(Il2CppPropertyDefinition property return PropertyIndices[propertyDefinition]; } + public static Il2CppTypeDefinition GetDeclaringTypeFromField(Il2CppFieldDefinition fieldDefinition) + { + if (LibCpp2IlMain.TheMetadata == null) return null!; + + if (FieldDeclaringTypes.Count == 0) + { + lock (FieldDeclaringTypes) + { + if (FieldDeclaringTypes.Count == 0) + { + foreach (var declaringType in LibCpp2IlMain.TheMetadata.typeDefs) + { + foreach (var field in declaringType.Fields ?? []) + { + FieldDeclaringTypes[field] = declaringType; + } + } + } + } + } + + return FieldDeclaringTypes[fieldDefinition]; + } + public static Il2CppType? GetTypeFromDefinition(Il2CppTypeDefinition definition) { if (LibCpp2IlMain.Binary == null)