Struct 를 Byte 로, Byte 를 Struct 로 변환하는 소스 입니다.
public static byte[] StructToByte(object obj)
{
int size = Marshal.SizeOf(obj);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
public static T ByteToStruct<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;
}
'Languages > C#' 카테고리의 다른 글
[ C# ] FTP (4) | 2013.02.26 |
---|---|
[ C# ] Object To Byte, Byte To Byte (0) | 2013.02.26 |
[ C# ] Win32 API MouseEvent (8) | 2010.12.07 |
[ C# ] C# FTP Download (3) | 2010.07.21 |
[ C# ] Default Sound Device 변경하기 (0) | 2010.07.19 |