.NET 8 Preview 2

Par:
fredericmazue

ven, 17/03/2023 - 13:40

Après .NET 8 Preview 1 qui se faisait remarquer par une amélioration de la prise en charge de Linux, Microsoft a publié .NET 8 preview 2 qui apporte diverses améliorations, parmi lesquelles nous remarquons la prise en charge de l'introspection pour les pointeurs de fonction. Les pointeurs de fonction ont été ajoutés dans le contexte de .NET 5 et C# 9, cependant, Microsoft n'avait alors pas ajouté d'expérience correspondante pour la fonctionnalité dans Reflection. Cette nouvelle fonctionnalité ajoute la possibilité d'obtenir des métadonnées de pointeur de fonction via Reflection, y compris les types de paramètres, le type de retour et les conventions d'appel.  Voici un exemple de code qui utilise cette nouvelle fonctionnalité : 

FieldInfo fieldInfo = typeof(MyClass).GetField(nameof(MyClass._fp));

// Obtain the function pointer type from a field. This used to be the 'IntPtr' type, now it's 'Type':
Type fpType = fieldInfo.FieldType;

// New methods to determine if a type is a function pointer:
Console.WriteLine(fpType.IsFunctionPointer); // True
Console.WriteLine(fpType.IsUnmanagedFunctionPointer); // True

// New methods to obtain the return and parameter types:
Console.WriteLine($"Return type: {fpType.GetFunctionPointerReturnType()}"); // System.Void

foreach (Type parameterType in fpType.GetFunctionPointerParameterTypes())
{
    Console.WriteLine($"Parameter type: {parameterType}"); // System.Int32&
}

// Access to custom modifiers and calling conventions requires a "modified type":
Type modifiedType = fieldInfo.GetModifiedFieldType();

// A modified type forwards most members to its underlying type which can be obtained with Type.UnderlyingSystemType:
Type normalType = modifiedType.UnderlyingSystemType;

// New methods to obtain the calling conventions:
foreach (Type callConv in modifiedType.GetFunctionPointerCallingConventions())
{
    Console.WriteLine($"Calling convention: {callConv}");
    // System.Runtime.CompilerServices.CallConvSuppressGCTransition
    // System.Runtime.CompilerServices.CallConvCdecl
}

// New methods to obtain the custom modifiers:
foreach (Type modreq in modifiedType.GetFunctionPointerParameterTypes()[0].GetRequiredCustomModifiers())
{    Console.WriteLine($"Required modifier for first parameter: {modreq }");
    // System.Runtime.InteropServices.InAttribute
}

// Sample class that contains a function pointer field:
public unsafe class MyClass
{
    public delegate* unmanaged[Cdecl, SuppressGCTransition]<in int, void> _fp;
}