C#中byte[]、struct、Intr間の相互変換
//byte[]structに変換【呼び出し時:Type type=typeof(byte);Struct II=(Struct)BytesToStruct(WW,type);public static object BytesToStruct(byte[] bytes, Type type) { int size = Marshal.SizeOf(type); IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.Copy(bytes, 0, buffer, size); return Marshal.PtrToStructure(buffer, type); } finally { Marshal.FreeHGlobal(buffer); } }//structをbyte[]public static byte[]StructToBytes(objectstructObj){int size=Marshall.SizeOf(structObj);InInInInInInInttr buffer=Marshal.AllochGlobal( size);try{Marshal.StructututureToPtr( structObj,buffer,false);byte[]bytes=new byte[size];Marshal. Copy(buffer,bytes,0,size);bytes;return bytes;}finally { Marshal.FreeHGlobal(buffer); } }
//byte[] Intptr
public static IntPtr BytesToIntptr(byte[] bytes)
{
int size = bytes.Length;
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, buffer, size);
return buffer;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}