컴퓨터 프로그래밍
[C#] byte[] 를 구조체로 바꾸기
orange code
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;
}
{
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);
{
public int x, y;
}
A a = ReadStruct<A>(buffer);