Skip to content

[API Proposal]: TypeMapping.TryGetValue, ITypeMapValue<TValue> and type targets to read type map data without exposing Type #138056

Description

@Sergio0694

Background and motivation

Interop type maps (#113362) map a key to a Type, and TypeMapping.GetOrCreateExternalTypeMapping<TGroup>() / GetOrCreateProxyTypeMapping<TGroup>() return those Type values. Consumers that only need data about the mapped entry have to go through reflection to get it. CsWinRT 3.0, for example, reads the marshaller, runtime class name, IID and vtable of a projected type from custom attributes on the returned type, with GetCustomAttribute and IsDefined. Libraries that map types to their own metadata representation (source generated shape registries, activation tables, converters) have the same need.

In Native AOT, handing out the Type makes every mapped type reflection visible, together with its attribute classes, their virtual methods, and everything reachable from them. Returning an instance or a delegate instead does not help: anyone can call GetType() on an instance, and the target of a delegate becomes reflection visible as soon as Delegate.Method is called anywhere in the program.

This proposes letting the target type provide the data itself, without ever exposing a Type:

  • The target type implements ITypeMapValue<TValue> (a static abstract getter), and new TypeMapping.TryGetValue overloads return the value. In Native AOT, when TValue is a struct whose fields are constants, string literals, function pointers or typeof results, ILC evaluates the getter at compile time and stores the result in the type map table, so the target type needs no reflection metadata and no attribute lookup. In other cases it emits a small stub that calls the getter. If a group is only used through TryGetValue, the Type-valued map is not generated for it. If the same group is also used through GetOrCreate*, the same table serves both.
  • Type map entries can be declared on a type instead of on the assembly, and the assembly (or another type) points to it with a new TypeMapTypeTargetAttribute<TGroup>. Reading the assembly attributes then does not have to go through thousands of entries (assembly attributes are commonly read at run time on CoreCLR, for example AssemblyMetadataAttribute), and a lookup can start at a given type (a local type map).

Measured on the Windows Store app (Native AOT, OptimizationPreference=Size, about 13,000 type map entries kept), comparing CsWinRT 3.0 using attributes and Type values against the same CsWinRT prototype migrated to TryGetValue (ten small value structs, one per group and kind):

WinStore.App.dll MSIX (estimated)
Attributes and Type values (baseline) 84,835,328 27,614,042
Typed values 82,376,192 (-2,459,136, -2.90%) 27,012,840 (-601,202)

The MSIX column is the image compressed at zlib level 6, as a proxy for its size in the package. It is not a measured MSIX build. Both builds include the ILC type loader gate from #137541.

API Proposal

 namespace System.Runtime.InteropServices;

+public interface ITypeMapValue<TValue>
+{
+    static abstract TValue Value { get; }
+}

-[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
+[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true)]
 public sealed class TypeMapAttribute<TTypeMapGroup> : Attribute
 {
     public TypeMapAttribute(string value, Type target);

     [RequiresUnreferencedCode("Interop types may be removed by trimming")]
     public TypeMapAttribute(string value, Type target, Type trimTarget);
 }

 [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
 public sealed class TypeMapAssemblyTargetAttribute<TTypeMapGroup> : Attribute
 {
     public TypeMapAssemblyTargetAttribute(string assemblyName);
 }

+[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true)]
+public sealed class TypeMapTypeTargetAttribute<TTypeMapGroup> : Attribute
+{
+    public TypeMapTypeTargetAttribute(Type type);
+}

-[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
+[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true)]
 public sealed class TypeMapAssociationAttribute<TTypeMapGroup> : Attribute
 {
     public TypeMapAssociationAttribute(Type source, Type proxy);
 }

 public static partial class TypeMapping
 {
+    [RequiresUnreferencedCode("Interop types may be removed by trimming")]
+    public static bool TryGetValue<TTypeMapGroup, TValue>(string key, [MaybeNullWhen(false)] out TValue value);

+    [RequiresUnreferencedCode("Interop types may be removed by trimming")]
+    public static bool TryGetValue<TTypeMapGroup, TValue>(Type key, [MaybeNullWhen(false)] out TValue value);

+    [RequiresUnreferencedCode("Interop types may be removed by trimming")]
+    public static bool TryGetValue<TTypeMapGroup, TTypeMapGroupOwner, TValue>(string key, [MaybeNullWhen(false)] out TValue value);

+    [RequiresUnreferencedCode("Interop types may be removed by trimming")]
+    public static bool TryGetValue<TTypeMapGroup, TTypeMapGroupOwner, TValue>(Type key, [MaybeNullWhen(false)] out TValue value);
 }

Values. TryGetValue looks up key in the external (string keys) or proxy (Type keys) type map of the group. It returns true and the value of the static getter if the key is found and the target type implements ITypeMapValue<TValue>, and false otherwise. A target type can implement the interface for several TValue types. The target type itself is never exposed.

  • TTypeMapGroup, TTypeMapGroupOwner and TValue have to be known statically at the call site (no generic parameters); calls are intrinsics for ILC, the trimmer and the analyzer, like the existing type map APIs.
  • TTypeMapGroupOwner cannot be a static class, since C# does not allow static classes as type arguments. Holder types that are only reached through TypeMapTypeTargetAttribute<TGroup> can be static.
  • The getter should be a simple expression without side effects. It can be evaluated ahead of time, not run at all, or run any number of times, possibly concurrently. The value is as visible to reflection as the code of the getter makes it (for example a typeof expression makes that type visible).
  • TValue can be any type. Reference types are not stored in the table: their getter runs at run time.
  • Keys are unrestricted: a Type key of the proxy map can be an interface or any other type. The restriction is on the target type, the type that provides the value. An interface target type has no implementation of the getter to call, so TryGetValue returns false for it. A value can still reference an interface with one extra hop: a class target type implements ITypeMapValue<TValue>, and its TValue holds typeof(IMyInterface). In Native AOT this is also fully pre-initialized.

Holder types. The entries (TypeMapAttribute<TGroup> and TypeMapAssociationAttribute<TGroup>) can be declared on a class. TypeMapTypeTargetAttribute<TGroup>(Type), on the assembly or on a class, points to a type that holds entries for the group, and the entries of the types it points to are followed transitively. The holder type is only a container for attributes: it is not constructed and not exposed. Entries declared on a class are only considered when the class is reachable through TypeMapTypeTargetAttribute<TGroup> from an assembly that is part of the type map of the group, or when it is the TTypeMapGroupOwner of a lookup (or reachable from it). Entries on any other class are ignored. Reachable entries are part of the type map of the group in the same way as entries declared on the assembly, so GetOrCreateExternalTypeMapping and GetOrCreateProxyTypeMapping see them too.

Scoped lookup. The overload with TTypeMapGroupOwner starts the lookup at that type: it considers the entries declared on TTypeMapGroupOwner and on the types reachable from it through TypeMapTypeTargetAttribute<TGroup>, and nothing else. This gives libraries a local type map that does not need whole program analysis and does not mix with the type maps of other libraries.

Runtimes. On CoreCLR the implementation uses reflection. Mono throws NotSupportedException, as for the existing type map APIs. Existing APIs and the output of apps that do not use the new APIs are unchanged.

Only the Try form is proposed. A throwing GetValue is a trivial wrapper that callers can add.

API Usage

A library that associates callbacks with a key (CsWinRT style). The target type is a marker that is never exposed, and the value is a struct of function pointers:

[assembly: TypeMap<WindowsRuntimeGroup>("Windows.Foundation.Uri", typeof(UriMarker), typeof(Uri))]

internal sealed class WindowsRuntimeGroup;

internal unsafe struct MarshallingInfo
{
    public delegate*<void*, object> CreateObject;
}

file sealed unsafe class UriMarker : ITypeMapValue<MarshallingInfo>
{
    public static MarshallingInfo Value => new() { CreateObject = &UriMarshaller.CreateObject };
}

internal static unsafe class Marshaller
{
    public static object? CreateObject(string runtimeClassName, void* thisPtr)
        => TypeMapping.TryGetValue<WindowsRuntimeGroup, MarshallingInfo>(runtimeClassName, out MarshallingInfo info)
            ? info.CreateObject(thisPtr)
            : null;
}

A library that maps types to its own metadata objects (source generated type shapes), with the entries declared on holder types linked from the assembly. ShapeMap links to a second holder, whose entries are followed too:

[assembly: TypeMapTypeTarget<ShapeGroup>(typeof(ShapeMap))]

internal sealed class ShapeGroup;

[TypeMapAssociation<ShapeGroup>(typeof(int), typeof(Int32Shape))]
[TypeMapAssociation<ShapeGroup>(typeof(string), typeof(StringShape))]
[TypeMapTypeTarget<ShapeGroup>(typeof(CollectionShapeMap))]
internal static class ShapeMap;

[TypeMapAssociation<ShapeGroup>(typeof(Dictionary<string, int>), typeof(DictionaryShape))]
internal static class CollectionShapeMap;

file sealed class Int32Shape : ITypeMapValue<ITypeShape>
{
    public static ITypeShape Value => Shapes.Int32;
}

file sealed class StringShape : ITypeMapValue<ITypeShape>
{
    public static ITypeShape Value => Shapes.String;
}

file sealed class DictionaryShape : ITypeMapValue<ITypeShape>
{
    public static ITypeShape Value => Shapes.DictionaryOfStringInt32;
}

public static class ShapeProvider
{
    public static ITypeShape? GetShape(Type type)
        => TypeMapping.TryGetValue<ShapeGroup, ITypeShape>(type, out ITypeShape? shape) ? shape : null;
}

A local type map. Nothing on the assembly points to LocalShapeMap, so its entries are only seen by lookups that start there:

internal sealed class LocalShapeGroup;

[TypeMapAssociation<LocalShapeGroup>(typeof(int), typeof(Int32Shape))]
internal sealed class LocalShapeMap;

internal static class LocalShapeProvider
{
    public static ITypeShape? GetShape(Type type)
        => TypeMapping.TryGetValue<LocalShapeGroup, LocalShapeMap, ITypeShape>(type, out ITypeShape? shape) ? shape : null;
}

Alternative Designs

  • Return Type and read attributes (current). Works, but keeps every mapped type, attribute class and the code reachable from their virtual methods reflection visible. This is the cost measured above.
  • Return instances or delegates. GetType() on an instance and Delegate.Method make the type or the target reflection visible again.
  • Return the custom attribute data (for example GetAttributesFrom<TGroup, TValue>(key) returning CustomAttributeData). Attribute arguments cannot express function pointers or callbacks, the data has to be decoded at run time, and the attribute classes stay reflection visible.
  • Create an instance of the target type (TryCreateInstance<TGroup>(key, out object)). It prevents pre-initialization (about 1 MB of additional .text on the Store app) and the constructed type needs its metadata. The static getter allows this usage too: a getter that is a factory returns an instance.
  • A dictionary or switch generated in the library. It roots every entry, which defeats the trim target conditions that are the reason type maps exist.
  • Data as TypeMap attribute arguments. Attribute arguments cannot express function pointers or structs.
  • A static abstract void Invoke(object? context) called through the type map with a context object that the target fills in. It works, but the call has to run at run time, so nothing folds into the table. On the same Store app it was 693,760 B larger than the typed values (83,069,952 B against 82,376,192 B).
  • Local type maps produced by whole program analysis and injected into the user assembly (Discover type maps from the group defining assembly #136606). The TTypeMapGroupOwner overloads give a local type map without whole program analysis.
  • Store type map entries in a custom metadata blob instead of attributes. It would avoid the assembly attribute cost on CoreCLR, but needs Roslyn support or IL rewriting after the build. Holder types get most of the benefit with existing attributes.
  • Replace GetOrCreate* with TryGetValue. GetOrCreate* stays for consumers that need the Type. A group used only through TryGetValue does not pay for the Type-valued map.
  • A GetValue that throws, in addition to TryGetValue. Can be built on top of TryGetValue by callers.
  • Constrain TValue to struct. Not needed. Reference types work, they just run the getter at run time instead of being stored in the table.
  • A consteval feature in C# instead of the getter being evaluated by ILC. The API works without any compile time evaluation (the getter runs at run time); evaluating it ahead of time is an optimization, like for the other patterns ILC pre-initializes (vtables, ComInterfaceEntry buffers).

Risks

  • The getter contract (it may not run, or run many times) is easy to violate with side effects. The documentation spells it out. Native AOT may never run the getter, while CoreCLR does.
  • A target type that does not implement ITypeMapValue<TValue> for the requested TValue, or a target interface, returns false silently, the same as a missing key. A target type that fails to load returns false on Native AOT but throws on CoreCLR.
  • CoreCLR uses reflection, and its trimmed behavior relies on the trimmer keeping the ITypeMapValue<TValue> implementations of target types.
  • Holder types, TypeMapTypeTargetAttribute<TGroup> and the TTypeMapGroupOwner overloads are not covered by the size numbers above. Their CoreCLR startup benefit and the comparison with the source generated type registries of consumers such as PolyType (Native AOT and JIT) are still to be measured.
  • This adds a second way to consume a type map next to GetOrCreate*. Expected consumers besides CsWinRT: PolyType, Npgsql, System.Runtime.InteropServices.JavaScript ([API Proposal] Typed factory attributes for type-map activation #137006) and local type maps ([API Proposal]: MakeWeakTypeReference as trimming indicator #74307).

Note

This issue was drafted with AI assistance (GitHub Copilot) and reviewed by the author. A working prototype of TryGetValue and ITypeMapValue<TValue> exists locally; the size numbers above come from full Store Native AOT builds with it. A draft PR with the implementation of those is #138065.

Activity

  1. added
    api-suggestion
    on Nov 21, 2026
  2. added
    untriaged
    on Nov 21, 2026
  3. dotnet-policy-service commented on Nov 21, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/interop-contrib
    See info in area-owners.md if you want to be subscribed.

  4. AaronRobinsonMSFT commented on Nov 21, 2026

    @AaronRobinsonMSFT
    Member

    Didn't we intentionally work with the CsWinRT team and decided on types and encoded data in the attributes to handle this? What has changed here?

  5. Sergio0694 commented on Nov 21, 2026

    @Sergio0694
    ContributorAuthor

    At the time we were told that encoding stuff in attributes was the most efficient way to do things (which was true, this needs additional ILC support). However in practice once tested end to end in a real world large app (e.g. the Store), the design turned out to be quite suboptimal, especially causing a ton of additional metadata (because a ton of types end up having to be marked as reflection visible due to attribute lookups, data being stored there not really be as efficient as possible, etc.). Plus minimizing binary size is becoming an increasingly critical requirement in general. I spent a bunch of time iterating through various shapes, and the one in the API proposal is the most efficient one: combined with ILC pre-initializing things this basically completely bypasses all attribute metadata, reflection rooting, and requires no code size increase either because everything is fully in .rdata.

    See binary size numbers above for reference where this saves 2.5 MB of binary size in the Store, for instance.

  6. AaronRobinsonMSFT commented on Nov 21, 2026

    @AaronRobinsonMSFT
    Member

    How will this interact with the existing GetOrCreateExternalTypeMapping and GetOrCreateProxyTypeMapping dictionaries? Don't they require the types to be stored anyways? Or is the assumption that if they are accessible from one of these new APIs they don't exist in the dictionaries?

  7. AaronRobinsonMSFT commented on Nov 21, 2026

    @AaronRobinsonMSFT
    Member

    If a group is only used through TryGetValue, the Type-valued map is not generated for it. If the same group is also used through GetOrCreate*, the same table serves both.

    Ah.

  8. Sergio0694 commented on Nov 21, 2026

    @Sergio0694
    ContributorAuthor

    Yeah I tried to have the implementation share the storage where possible. The main difference is if you just use the new Try* methods, and use struct types with fields that support pre-initialization, you actually get the best codegen possible because the entire flow gets fully pre-initialized (so the whole static abstract call is also skipped, the whole body of each target is just pre-initialized into frozen data). The prototype supports this for all types that CsWinRT (and most consumers) could need: function pointers, strings, and Type instances.

    Of course, the assumption is that people wanting to optimize things (e.g. in CsWinRT) would just 100% switch to the new APIs.

  9. jkotas commented on Nov 21, 2026

    @jkotas
    Member

    or a mapped interface (which is not supported), returns false silently,

    This seems to be an arbitrary limitation of the proposed design. I think that there is a high chance that the next person that comes along is going to ask for it to be lifted. This proposal provides a scheme to associate custom metadata with types, in more AOT-friendly way than attributes, so it would be useful for it to be as powerful as attributes.

    @eiriktsarpalis Do you think that you would be able to take advantage of an API like this in https://github.com/eiriktsarpalis/PolyType in the source-generated mode? If yes, what's missing from this proposal to make that possible?

  10. eiriktsarpalis commented on Nov 21, 2026

    @eiriktsarpalis
    Member

    I don't see a compelling use case for PolyType. The library currently uses static abstracts and witness types (same as Serde.NET) to map types to shapes in a typesafe manner.

  11. AaronRobinsonMSFT commented on Nov 21, 2026

    @AaronRobinsonMSFT
    Member

    This proposal provides a scheme to associate custom metadata with types, in more AOT-friendly way than attributes, so it would be useful for it to be as powerful as attributes.

    The interface and static abstracts seem like utilizing a language feature when the real problem as defined seems to be "give me the custom attribute data, not the attached type". Why not something akin to:

    public static Span<CustomAttributeData> GetAttributesFrom<TTypeMapGroup, TValue>(string key);
    public static Span<CustomAttributeData> GetAttributesFrom<TTypeMapGroup, TValue>(Type key);
  12. Sergio0694 commented on Nov 21, 2026

    @Sergio0694
    ContributorAuthor

    "This seems to be an arbitrary limitation of the proposed design. I think that there is a high chance that the next person that comes along is going to ask for it to be lifted. This proposal provides a scheme to associate custom metadata with types, in more AOT-friendly way than attributes, so it would be useful for it to be as powerful as attributes."

    @jkotas do you mean if people just wanted to get back a Type for the lookup key? Isn't that the same as how the interop type map works today in that case? Or are you referring to something else, can you make an example? 😅

    "Why not something akin to [...]"

    @AaronRobinsonMSFT there's a few issues with that approach compared to the proposed API:

    • A common scenario (e.g. for CsWinRT, but I can imagine other libs like serializers wanting this) is to associate one or more callbacks with a type map key. The new API lets you return a value that has one or more function pointers as fields, so you can then just invoke those as needed. For instance, in CsWinRT we need this for the callbacks to marshal instances. If you just returned custom attribute data, you'd have no way to encode a parameter which is some kind of callback.
    • The design of the proposed API is such that everything can be completely pre-initialized. There's no parsing/decoding/activation of any kind at runtime to retrieve the associated values. You can lookup a value type that has e.g. an arbitrary number of fields of function pointers, string, or Type instances, and ILC will fully pre-initialize the entire buffer for each of those values, completely trim away the target type and interface implementation, and just return you a direct copy from that .rdata section. Function pointers get the hardcoded address of the target method, string go in the FOH, and Type just also gets precompiled. Additionally in ILC: reuse frozen strings as keys of external type maps #138066 this is extended more so that ILC can then also reuse those same FOH strings as storage for the interop type map keys, when they represent the same text (instead of storing both the UTF8-encoded buffer for the key, and the FOH string for the value).
  13. AaronRobinsonMSFT commented on Nov 21, 2026

    @AaronRobinsonMSFT
    Member

    The design of the proposed API is such that everything can be completely pre-initialized.

    This is relying on the current interpreter though, correct? As in the implementation of static abstract TValue Value { get; } is going to get evaluated at compile time and then encoded. Which means what is being proposed here is the slow creep of everything being evaluated at compile time. Not a deal breaker, but basically becomes consteval for C#.

    We already sort of have this with how module or static initializers (can't recall which or both) are interpreted with a min set of features. This is expanding that to a static property. I think what I'm alluding to here is what you really want is a consteval feature in C# and if so, maybe that is what we should be building instead of the consistent slow creep since .NET 8 of interop APIs for CsWinRT.

  14. 28 remaining items

  15. Sergio0694 commented on Nov 24, 2026

    @Sergio0694
    ContributorAuthor

    @eiriktsarpalis @jkotas here's some benchmarks with a fork of PolyType using the new type map API and setup (with the owner type):

    Area Scenario Switch (today) Type map Change
    NativeAOT size Forest, 100 registered, 1 used 2.73 MB 2.24 MB -17.7%
    Forest, 1,000 7.23 MB 2.30 MB -68.2%
    Forest, 2,000 12.23 MB 2.37 MB -80.7%
    Tree (all reachable), 100 2.88 MB 2.88 MB +0.0%
    Tree, 1,000 8.61 MB 8.54 MB -0.8%
    Tree, 2,000 14.99 MB 14.86 MB -0.9%
    NativeAOT startup Flat 50, first roundtrip 38.32 ms no detectable difference (paired, 50 rounds) ~0
    NativeAOT lookup 1,000 lookups per type, Type key 280 ns 150 ns -46%
    Same, string key 280 ns 410 to 500 ns +46% to +79%
    CoreCLR, app JIT Flat 50, first roundtrip 247.2 ms +0.7 to +2.5 ms +0.3% to +1.0%
    Tree 1,000, first roundtrip 4,185 ms -16 to -25 ms -0.4% to -0.6%
    Tree 1,000, first GetTypeShape 25.9 ms 9.3 to 10.3 ms -60%
    CoreCLR, app R2R Flat 50, first roundtrip 152.8 ms +2.0 to +2.9 ms +1.3% to +1.9%
    Tree 1,000, first roundtrip 2,686 ms +2.4 to +14.9 ms slightly worse

    The binary size numbers in particular are way better on NAOT, which is expected.
    Also note that PolyType only does the lookup by type, so that perf regression for string lookups wouldn't matter at all for it.

  16. eiriktsarpalis commented on Nov 24, 2026

    @eiriktsarpalis
    Member

    I evaluated the proposed typed TypeMap against PolyType's generated registry on CoreCLR and Native AOT: prototype report and measurements.

    In the sparse 500-node Native AOT workload, TypeMap reduced executable size by 60.6% and eliminated warm-lookup allocations. However, the prototype also omitted registered interface, abstract-class and unallocated-class shapes that the existing registry returned. CoreCLR warm lookups were slower, and assembly-level registrations increased attribute-enumeration cost. The proposed holder-type registration was not implemented in the runtime revision tested.

    The prototype, measurements and report were produced with GitHub Copilot and have not been independently reviewed.

  17. eiriktsarpalis commented on Nov 24, 2026

    @eiriktsarpalis
    Member

    @Sergio0694 I missed your response. Looks promising, but would a polyfill be made available to older supported runtimes?

  18. Sergio0694 commented on Nov 24, 2026

    @Sergio0694
    ContributorAuthor

    I don't think so, this requires a lot of runtime support, so it'd most likely only work on .NET 12+, or it'd have to be backported.

  19. Sergio0694 commented on Nov 24, 2026

    @Sergio0694
    ContributorAuthor

    @jkoritzinsky nit: if the type parameter for the class with the attributes is named TTypeMapGroupOwner, should TypeMapTypeTargetAttribute actually be named TypeMapOwnerAttribute for consistency? Or maybe TypeMapOwnerTypeAttibute. 🤔

  20. jkoritzinsky commented on Nov 24, 2026

    @jkoritzinsky
    Member

    I don't think so, because the point is that traversal starts at that type, whereas the attributes specify that traversal should include that type.

  21. Sergio0694 commented on Nov 24, 2026

    @Sergio0694
    ContributorAuthor

    I see what you mean, alright. Are we missing anything else to mark this proposal as ready for review?

  22. NinoFloris commented on Nov 24, 2026

    @NinoFloris
    Contributor

    I do like the idea of hanging the attributes off of a type, but I'd like one more addition if possible (would serve PolyType, Npgsql, and other scenarios that aren't "global application model or interop framework" scenarios): Add an overload of TypeMapping.TryGetValue that has 3 generic parameters:

    TypeMapping.TryGetValue<TTypeMapGroup, TTypeMapGroupOwner, TValue>. This overload would start type map traversal at TTypeMapGroupOwner (same requirements as TTypeMapGroup). I'd also add support for TypeMapTypeTarget to be on a class too to support this.

    This would provide us a mechanism other than #136606 to enable more "local" type maps and provide a UX for users looking to implement #74307 that doesn't require whole-program analysis and injecting logic into the user's assembly.

    @jkotas what do you think of this?

    It probably works for us. I wrote a bit about it on discord

  23. jkotas commented on Nov 24, 2026

    @jkotas
    Member

    internal unsafe struct MarshallingInfo
    {
    ....
    };

    TypeMapping.TryGetValue<WindowsRuntimeGroup, MarshallingInfo>(runtimeClassName, out MarshallingInfo info)

    This shape assume that TValue is a small struct, so it is ok to copy it around. What is going to be the size of TValue for CsWinRT and other cases? I am wondering whether we can make the overheads smaller across different scenarios.

  24. Sergio0694 commented on Nov 24, 2026

    @Sergio0694
    ContributorAuthor

    In the current prototype, the largest is 24 bytes. Even if e.g. we merged some of the types together, I doubt they'd get too large (e.g. say more than 48 bytes). Also merging them too much doesn't seem beneficial for other reasons (not all values are always needed/present). I was thinking about potentially also having an overload returning the value as ref readonly but not sure it's worth it, at least in our case 🤔

    Say, something like:

    public static ref readonly TValue TryGetValue<TTypeMapGroup, TValue>(Type key) where TValue : struct;

    That returns a null ref for missing items, or otherwise something like CollectionsMarshal:

    public static ref readonly TValue TryGetValue<TTypeMapGroup, TValue>(Type key, out bool exists) where TValue : struct;
  25. jkotas commented on Nov 25, 2026

    @jkotas
    Member

    Did you get pre-initialization working for PolyType?

  26. Sergio0694 commented on Nov 25, 2026

    @Sergio0694
    ContributorAuthor

    Just to make sure we're referring to the same thing, the prototype would be this:

    file sealed unsafe class Dictionary_String_Int32Proxy : ITypeMapValue<ITypeShape>
    {
        public static ITypeShape Value => Dictionary_String_Int32;
    }

    And no, pre-initialization doesn't work here, because those shape instances (e.g. Dictionary_String_Int32) are lazily-instantiated objects, so you just go through the small Value stub at runtime to invoke it. I assumed that was by design in PolyType since those objects have a bunch of lazy initialization and internal cache management. In theory, if you removed all that lazy initialization and made all shapes immutable (as in with no state) such that they could just be frozen in a static readonly field, then yes the whole thing should pre-initialize just fine (same as it does for Type or string objects too when those can be frozen, if you just pass typeof(Foo) or a constant string literal).

    That is, all these reference type values support pre-initialization as well:

    file sealed unsafe class TestProxy : ITypeMapValue<Type>
    {
        public static Type Value => typeof(Foo);
    }
    file sealed unsafe class TestProxy : ITypeMapValue<string>
    {
        public static string Value => "Foo";
    }
    file sealed unsafe class TestProxy: ITypeMapValue<IFoo>
    {
        public static IFoo Value => FooImpl.Instance;
    }
    
    interface IFoo;
    
    file sealed class FooImpl : IFoo
    {
        public static readonly FooImpl Instance = new();
    }
  27. jkotas commented on Nov 25, 2026

    @jkotas
    Member

    you just go through the small Value stub at runtime to invoke it

    This is actually a very good point. We go through quite a few layers just to get to a small stub: from attributes to a type that implements an interface, which then allows us to look up a stub that we ultimately invoke to retrieve the value. It feels like a few too many indirection.

    How about we flip it and orient it around the list of methods? Types are natural containers for lists of methods. Something like:

    internal static class Shapes
    {
        [TypeMapAssociation(typeof(int))]
        static ITypeShape Int32 => ...;
    
        [TypeMapAssociation(typeof(string))]
        static ITypeShape String => ...;
    
        [TypeMapAssociation(typeof(Dictionary<string, int>))]
        static ITypeShape DictionaryOfStringInt32 => ...;
    }
    
    public static class ShapeProvider
    {
        public static ITypeShape? GetShape(Type type)
            => TypeMapping.TryGetValue<Shapes>(type, out ITypeShape? shape) ? shape : null;
    }
  28. Sergio0694 commented on Nov 25, 2026

    @Sergio0694
    ContributorAuthor

    "We go through quite a few layers just to get to a small stub: from attributes to a type that implements an interface, which then allows us to look up a stub that we ultimately invoke to retrieve the value. It feels like a few too many indirection."

    I might have phrased that poorly. To clarify, by "stub" I didn't mean to say that we're generating some additional special bit of code or something, I just meant the static abstract method you implemented yourself. That is, it's just that in the special case where the whole thing gets pre-initialize, the type map gets smart enough that it just stores the address of the constant data to return, and you just get that directly. Otherwise, you just go through the "normal" path, which is to just invoke your method at runtime. So like there's no "stub" in the sense of something additional that the runtime generates, it's just your own code working normally.

    "How about we flip it and orient it around the list of methods?"

    I don't feel too strongly about the API shape as long as the functionality is the same, if there's a strong preference for this we would just need to make sure that all the same scenarios would still be supported (including when registrations are split across a bunch of different assemblies, not just one). Imho I do prefer the attributes, as it's consistent with how the type map currently works, and it matches more of this "declaring special metadata" mental model that I have for the interop type map.

    Worth noting though, you'd still have the same exact "stub" in your proposal too anyway. That is, if a given target isn't pre-initialized, going through the type map just ends up calling your method to get the value at runtime. So like that would be the same anyway.

  29. jkotas commented on Nov 25, 2026

    @jkotas
    Member

    Worth noting though, you'd still have the same exact "stub" in your proposal too anyway

    Right, the benefit is that the extra indirections between the attribute and the stub are gone. I expect it to have significantly smaller costs (startup time, binary size) outside the preinitialized NAOT case. We may want to get some numbers to confirm. As I have said above, if we do anything here, it needs to fix the problem for good. I do not want another suboptimal design.

    I am not sure whether connecting the new typemap with the existing typemap is a good thing. There are two cases:

    • You are exclusively on the new scheme that returns values instead types. You do not care about the existing typemap.
    • You want to support mix and match of both schemes. It means you need to call both new API and then the existing API as a fallback. You do not need the existing API to return anything that the new API returns since it would be redundant.

    So, I think it is preferable for the new typemap to be disjoint from the existing typemap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Runtime.InteropServices

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions