Skip to content

Q: AOT and composite type reflection #63670

Closed
@tmds

Description

@tmds

I'm trying to make some code AOT friendly, and I'm not sure how to go about it.

The code uses the .NET type system to represent protocol types. The types can be basic types, but there are also composite types such as arrays, structs, and dictionaries.

The following example uses MakeGenericMethod to deal with the composite types, and I'm not sure that will work with AOT? and what I can do to to make it AOT friendly?

using System.Reflection;

Writer writer = default;
writer.WriteDictionary(new Dictionary<int, IDictionary<int, int>> { { 1, new Dictionary<int, int> { { 2, 3 } } } });

ref struct Writer
{
    private delegate void ValueWriter(ref Writer writer, object value);

    public void WriteDictionary<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
    {
        foreach (var item in dictionary)
        {
            Write<TKey>(item.Key);
            Write<TValue>(item.Value);
        }
    }

    public void WriteInt(int i)
    {
        Console.WriteLine(i);
    }

    private static void WriteDictionaryCore<TKey, TValue>(ref Writer writer, object o)
    {
        writer.WriteDictionary<TKey, TValue>((IDictionary<TKey, TValue>)o);
    }

    private void WriteDictionaryTyped(Type keyType, Type valueType, object o)
    {
        var method = typeof(Writer).GetMethod(nameof(WriteDictionaryCore), BindingFlags.Static | BindingFlags.NonPublic)!
            .MakeGenericMethod(new[] { keyType, valueType });
        var dlg = method!.CreateDelegate<ValueWriter>();
        dlg.Invoke(ref this, o);
    }

    private void Write<T>(T value)
    {
        if (typeof(T) == typeof(int))
        {
            WriteInt((int)(object)value!);
            return;
        }
        else if (typeof(T).GetGenericTypeDefinition() == typeof(IDictionary<,>))
        {
            WriteDictionaryTyped(typeof(T).GenericTypeArguments[0], typeof(T).GenericTypeArguments[1], (object)value!);
            return;
        }
        throw new NotSupportedException(typeof(T).FullName);
    }
}

cc @MichalStrehovsky

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-NativeAOT-coreclrquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions