怎么把一个结构或类实例转换成字节数组? 可以用 Serializable 类进行串行化. 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 既然是struct,也可以用指针实现——但是最好为struct指定StructLayout属性。 这个问题有两个关键点:1.如何将STRUCT转换为字节数组;2.如何指定平台以1为单位分配空间而不是以默认大小。1.如何将STRUCT转换为字节数组;public struct YourStruct{ // only value-types possible here:public int First;public long Second;public double Third;}static unsafe byte[] YourStructToBytes( YourStruct s ){byte[] arr = new byte[ sizeof(YourStruct) ];fixed( byte* parr = arr ){ *((YourStruct*)parr) = s; }return arr;}static unsafe YourStruct BytesToYourStruct( byte[] arr ){if( arr.Length < sizeof(YourStruct) )throw new ArgumentException();YourStruct s;fixed( byte* parr = arr ){ s = *((YourStruct*)parr); }return s;}// usage:YourStruct s0;s0.First = 1;s0.Second = 2;s0.Third = 3.5;byte[] ab = YourStructToBytes( s0 );// reverse:YourStruct s1 = BytesToYourStruct( ab );2.如何指定平台以1为单位对齐内存空间而不是以默认大小。使用StructLayoutAttribute类a.using System.Runtime.InteropServices;b.在需要指定对齐方式的STRUCT前加入 [StructLayout(LayoutKind.Sequential, Pack=1)] 求正则表达式分析 <img alt="..." src="...",""中的内容,alt在src的左边和右边都有可能 在winform中如何将动态数据填充到有一定格式的Excel模板中 C#如何实现GIS 求方法 对 Point的 不解 请教,窗口关闭事件! C#里的float和double类型问题! c#怎样在屏幕上高效画点? 多播委托处理事件时的异常处理 请教 WebForm问题?急!急!急 请问在xp下可以安装运行vs studio.net吗?为什么我安装了无法运行? 在C#里怎么用IE样式的BUTTON和SCROLL?怎么写CTRL ALT DEL看不到的应用程序?
1.如何将STRUCT转换为字节数组;
2.如何指定平台以1为单位分配空间而不是以默认大小。1.如何将STRUCT转换为字节数组;
public struct YourStruct
{ // only value-types possible here:
public int First;
public long Second;
public double Third;
}static unsafe byte[] YourStructToBytes( YourStruct s )
{
byte[] arr = new byte[ sizeof(YourStruct) ];
fixed( byte* parr = arr )
{ *((YourStruct*)parr) = s; }
return arr;
}static unsafe YourStruct BytesToYourStruct( byte[] arr )
{
if( arr.Length < sizeof(YourStruct) )
throw new ArgumentException();YourStruct s;
fixed( byte* parr = arr )
{ s = *((YourStruct*)parr); }
return s;
}// usage:
YourStruct s0;
s0.First = 1;
s0.Second = 2;
s0.Third = 3.5;
byte[] ab = YourStructToBytes( s0 );
// reverse:
YourStruct s1 = BytesToYourStruct( ab );
2.如何指定平台以1为单位对齐内存空间而不是以默认大小。
使用StructLayoutAttribute类
a.using System.Runtime.InteropServices;
b.在需要指定对齐方式的STRUCT前加入
[StructLayout(LayoutKind.Sequential, Pack=1)]