컴퓨터 프로그래밍2009. 12. 28. 23:18
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