0

I'm trying to map the IL code for ASP.CORE method ReadUnaligned as defined here in .NET Frameword using DynamicMethod following this example.

When trying to run the code, I get the "Common Language Runtime detected an invalid program." error.

My code:

private delegate T ReadUnalignedInvoker<T>(ref byte input);

private delegate TReturn OneParameter<TReturn, TParameter0>(TParameter0 p0);

public static T ReadUnaligned<T, U>(U source)
{
    Type[] methodArgsTypes = { typeof(U) };

    var dm = new DynamicMethod("ReadUnaligned", typeof(T), methodArgsTypes, typeof(SizeHelper).Module);
    ILGenerator il = dm.GetILGenerator();

    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Unaligned, (byte)0x1);
    il.Emit(OpCodes.Ldobj);
    il.Emit(OpCodes.Ret);

    OneParameter<T, U> invoker = (OneParameter<T, U>)dm.CreateDelegate(typeof(OneParameter<T, U>));

    return invoker(source);
    }

The call to the method is:

var buffer = new byte[Unsafe.SizeOf<TStructure>()];

ReadProcessMemory(_processHandle, baseAddress, ref buffer[0], buffer.Length, out var numberOfBytesRead);

ReadUnaligned<TStructure, byte>(buffer[0]);

Where ReadProcessMemory is taken from kernel32.dll

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool ReadProcessMemory(SafeProcessHandle processHandle, IntPtr baseAddress, ref byte buffer, int bufferSize, out int numberOfBytesRead);

Any idea what I'm doing wrong?

4

0 回答 0