Wouldn’t it be like this job?
using System.Runtime.InteropServices; public static T Read<T>(IntPtr ptr) where T : struct { return (T)Marshal.PtrToStructure(ptr, typeof(T)); }
This will only work with structures, you will need to consider sorting strings as special not general if you need it.
A simple check to make sure it works:
var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int))); var three = 3; Marshal.StructureToPtr(three, ptr, true); var data = Read<int>(ptr); Debug.Assert(data == three);
source share