Skip to content

[API Proposal]: Get the managed size of a System.Type instance #97344

@jkoritzinsky

Description

@jkoritzinsky

Background and motivation

As part of the same problem as #97341, we have a scenario where we have a System.Type, we cannot rewrite the code in an AOT-safe manner to represent the type as a generic argument, and we want to be able to call Unsafe.SizeOf<T> for our System.Type instance.

This issue proposes a new method to get the size of the instance of a managed type from its RuntimeTypeHandle.

API Proposal

namespace System.Runtime.CompilerServices;

public class RuntimeHelpers
{
+    public static int SizeOf(RuntimeTypeHandle type);
}

API Usage

var abi_element_size = RuntimeHelpers.SizeOf(AbiType.TypeHandle);
var byte_length = length * abi_element_size;
m._array = Marshal.AllocCoTaskMem(byte_length);
m._marshalers = new object[length];
var element = (byte*)m._array.ToPointer();
for (int i = 0; i < length; i++)
{
    m._marshalers[i] = Marshaler<T>.CreateMarshaler(array[i]);
    Marshaler<T>.CopyAbi(m._marshalers[i], (IntPtr)element);
    element += abi_element_size;
}

Alternative Designs

We could place the API on System.Runtime.CompilerServices.Unsafe next to SizeOf<T>().

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Runtimein-prThere is an active PR which will close this issue when it is merged

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions