Files
HexUnlocked/src/dumper/struct-mapper.cs
T

50 lines
1.6 KiB
C#

using CUE4Parse.UE4.Assets.Objects;
using System.Reflection;
public static class StructMapper
{
public static T MapToStruct<T>(this FStructFallback fallback) where T : struct
{
object result = new T();
var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var field in fields)
{
if (field.FieldType.IsArray)
{
var prop = fallback.Properties.FirstOrDefault(p => p.Name.Text == field.Name);
if (prop?.Tag != null)
{
var value = prop.Tag.GetValue(field.FieldType);
field.SetValue(result, value);
}
continue;
}
try
{
var method = typeof(CUE4Parse.UE4.Assets.Exports.AbstractPropertyHolder)
.GetMethods()
.FirstOrDefault(m => m.Name == "GetOrDefault" && m.GetGenericArguments().Length == 1);
if (method != null)
{
var genericMethod = method.MakeGenericMethod(field.FieldType);
var value = genericMethod.Invoke(fallback, new object[] { field.Name, null!, StringComparison.Ordinal });
if (value != null)
{
field.SetValue(result, value);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Mapping failed for {field.Name}: {ex.Message}");
}
}
return (T)result;
}
}