private static T ReadStruct<T>(byte[] buffer) where T : struct
{
    int size = Marshal.SizeOf(typeof(T));
    if (size > buffer.Length)
        throw new Exception();
    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.Copy(buffer, 0, ptr, size);
    T obj = (T)Marshal.PtrToStructure(ptr, typeof(T));
    Marshal.FreeHGlobal(ptr);
    return obj;


ex)
struct A
{
    public int x, y;
}

A a = ReadStruct<A>(buffer);
Posted by orange code

티스토리 툴바