C# struct和byte[]之间的转化
2017-12-22 14:57
267 查看
这里只有两个函数:
using System.Text;
using System.Globalization;
// Summary:
// convert a struct data to list<byte>
//
public 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);
}
}
public 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);
}
}
using System.Text;
using System.Globalization;
// Summary:
// convert a struct data to list<byte>
//
public 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);
}
}
public 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);
}
}
相关文章推荐
- Java中byte[]与int之间的转化
- Android中Bitmap, Drawable, Byte,ID之间的转化
- byte数组和其他数据类型之间的转化
- Android中Bitmap, Drawable, Byte,ID之间的转化
- android----Bitmap / Drawable / byte[] 之间相互转化
- 【C#】byte[]数组中有值大于127时与string之间的相互转化
- Bitmap与Drawable,byte[]之间的转化
- Android中Bitmap, Drawable, Byte,ID之间的转化
- Bitmap与Drawable,byte[]之间的转化
- Android中Bitmap, Drawable, Byte,ID之间的转化
- Android中Bitmap, Drawable, Byte,ID之间的转化
- 字符串与十六进制与byte和十进制之间的转化
- Bitmap, Drawable, Byte之间的转化
- Android中Bitmap, Drawable, Byte,ID之间的转化
- java byte/char/string/int之间的转化
- Bitmap与Drawable,byte[]之间的转化
- Android中Bitmap, Drawable, Byte,ID之间的转化
- Android中Bitmap Drawable Byte之间的转化
- Android中Bitmap,byte[],Drawable之间的相互转化
- Android中Bitmap, Drawable, Byte,ID之间的转化