structとbyte[]の相互変換(Marshalクラスで実現)
2126 ワード
1、structをbyte[]に変換
static
byte
[] StructToBytes(
object
structObj){
int
size
=
Marshal.SizeOf(structObj); IntPtr buffer
=
Marshal.AllocHGlobal(size);
try
{ Marshal.StructureToPtr(structObj, buffer,
false
);
byte
[] bytes
=
new
byte
[size]; Marshal.Copy(buffer, bytes,
0
, size);
return
bytes; }
finally
{ Marshal.FreeHGlobal(buffer); }}
2、byte[]をstructに変換
static
byte
[] StructToBytes(
object
structObj){
int
size
=
Marshal.SizeOf(structObj); IntPtr buffer
=
Marshal.AllocHGlobal(size);
try
{ Marshal.StructureToPtr(structObj, buffer,
false
);
byte
[] bytes
=
new
byte
[size]; Marshal.Copy(buffer, bytes,
0
, size);
return
bytes; }
finally
{ Marshal.FreeHGlobal(buffer); }}
2、byte[]をstructに変換
static
object
BytesToStruct(
byte
[] bytes, Type strcutType)
{
int
size
=
Marshal.SizeOf(strcutType);
IntPtr buffer
=
Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes,
0
, buffer, size);
return
Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}