mardi 13 avril 2021

Using Reflection to access private unsafe pointer fields

Let there be the following class:

public class SomeClass
{
    private unsafe void* mPtr;
}

What is the proper way to access the value of mPtr using Reflection?

Here is how I'm trying to do it:

using System;

public class SomeClass
{
    private unsafe void* mPtr = (void*)42;
}

public class Program
{
    public static unsafe void Main()
    {
        System.Reflection.FieldInfo ptrFieldInfo = typeof(SomeClass).GetField("mPtr", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        
        SomeClass obj = new SomeClass();
        
        void* ptr = System.Reflection.Pointer.Unbox(ptrFieldInfo.GetValue(obj));
        
        Console.WriteLine("ptr = " + (int)ptr);
    }
}

The expected output is: ptr = 42

But, running this I get System.NullReferenceException originating from System.Reflection.MonoField.GetValueInternal.

Am I encountering this Mono bug? If yes, is there a workaround? Or am I doing it wrong?





Aucun commentaire:

Enregistrer un commentaire