Repository navigation
Description
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 newTypeMapping.TryGetValueoverloads return the value. In Native AOT, whenTValueis a struct whose fields are constants, string literals, function pointers ortypeofresults, 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 throughTryGetValue, theType-valued map is not generated for it. If the same group is also used throughGetOrCreate*, 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 exampleAssemblyMetadataAttribute), 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,TTypeMapGroupOwnerandTValuehave 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.TTypeMapGroupOwnercannot be a static class, since C# does not allow static classes as type arguments. Holder types that are only reached throughTypeMapTypeTargetAttribute<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
typeofexpression makes that type visible). TValuecan be any type. Reference types are not stored in the table: their getter runs at run time.- Keys are unrestricted: a
Typekey 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, soTryGetValuereturnsfalsefor it. A value can still reference an interface with one extra hop: a class target type implementsITypeMapValue<TValue>, and itsTValueholdstypeof(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
Typeand 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 andDelegate.Methodmake the type or the target reflection visible again. - Return the custom attribute data (for example
GetAttributesFrom<TGroup, TValue>(key)returningCustomAttributeData). 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.texton 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
switchgenerated in the library. It roots every entry, which defeats the trim target conditions that are the reason type maps exist. - Data as
TypeMapattribute 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
TTypeMapGroupOwneroverloads 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*withTryGetValue.GetOrCreate*stays for consumers that need theType. A group used only throughTryGetValuedoes not pay for theType-valued map. - A
GetValuethat throws, in addition toTryGetValue. Can be built on top ofTryGetValueby callers. - Constrain
TValuetostruct. Not needed. Reference types work, they just run the getter at run time instead of being stored in the table. - A
constevalfeature 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,ComInterfaceEntrybuffers).
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 requestedTValue, or a target interface, returnsfalsesilently, the same as a missing key. A target type that fails to load returnsfalseon 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 theTTypeMapGroupOwneroverloads 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.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNo status
Activity
dotnet-policy-service commentedon Nov 21, 2026
Tagging subscribers to this area: @dotnet/interop-contrib
See info in area-owners.md if you want to be subscribed.
AaronRobinsonMSFT commentedon Nov 21, 2026
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?
Sergio0694 commentedon Nov 21, 2026
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.
AaronRobinsonMSFT commentedon Nov 21, 2026
How will this interact with the existing
GetOrCreateExternalTypeMappingandGetOrCreateProxyTypeMappingdictionaries? 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?AaronRobinsonMSFT commentedon Nov 21, 2026
Ah.
Sergio0694 commentedon Nov 21, 2026
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, andTypeinstances.Of course, the assumption is that people wanting to optimize things (e.g. in CsWinRT) would just 100% switch to the new APIs.
jkotas commentedon Nov 21, 2026
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?
eiriktsarpalis commentedon Nov 21, 2026
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.
AaronRobinsonMSFT commentedon Nov 21, 2026
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:
Sergio0694 commentedon Nov 21, 2026
@jkotas do you mean if people just wanted to get back a
Typefor 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? 😅@AaronRobinsonMSFT there's a few issues with that approach compared to the proposed API:
string, orTypeinstances, 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.rdatasection. Function pointers get the hardcoded address of the target method,stringgo in theFOH, andTypejust 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 FOHstringfor the value).AaronRobinsonMSFT commentedon Nov 21, 2026
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 becomesconstevalfor 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
constevalfeature 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.28 remaining items
Sergio0694 commentedon Nov 24, 2026
@eiriktsarpalis @jkotas here's some benchmarks with a fork of PolyType using the new type map API and setup (with the owner type):
TypekeyGetTypeShapeThe 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
stringlookups wouldn't matter at all for it.eiriktsarpalis commentedon Nov 24, 2026
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.
eiriktsarpalis commentedon Nov 24, 2026
@Sergio0694 I missed your response. Looks promising, but would a polyfill be made available to older supported runtimes?
Sergio0694 commentedon Nov 24, 2026
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.
Sergio0694 commentedon Nov 24, 2026
@jkoritzinsky nit: if the type parameter for the class with the attributes is named
TTypeMapGroupOwner, shouldTypeMapTypeTargetAttributeactually be namedTypeMapOwnerAttributefor consistency? Or maybeTypeMapOwnerTypeAttibute. 🤔jkoritzinsky commentedon Nov 24, 2026
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.
Sergio0694 commentedon Nov 24, 2026
I see what you mean, alright. Are we missing anything else to mark this proposal as ready for review?
NinoFloris commentedon Nov 24, 2026
It probably works for us. I wrote a bit about it on discord
jkotas commentedon Nov 24, 2026
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.
Sergio0694 commentedon Nov 24, 2026
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 readonlybut not sure it's worth it, at least in our case 🤔Say, something like:
That returns a null ref for missing items, or otherwise something like
CollectionsMarshal:jkotas commentedon Nov 25, 2026
Did you get pre-initialization working for PolyType?
Sergio0694 commentedon Nov 25, 2026
Just to make sure we're referring to the same thing, the prototype would be this:
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 smallValuestub 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 astatic readonlyfield, then yes the whole thing should pre-initialize just fine (same as it does forTypeorstringobjects too when those can be frozen, if you just passtypeof(Foo)or a constant string literal).That is, all these reference type values support pre-initialization as well:
jkotas commentedon Nov 25, 2026
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:
Sergio0694 commentedon Nov 25, 2026
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.
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.
jkotas commentedon Nov 25, 2026
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:
So, I think it is preferable for the new typemap to be disjoint from the existing typemap.