http://blog.163.com/adslxk@126/blog/static/10061067120098445849265/
在写C#TCP通信程序时,发送数据时,只能发送byte数组,处理起来比较麻烦不说,如果是和VC6.0等写的程序通信的话,很多的都是传送结构体,在VC6.0中可以很方便的把一个char[]数组转换为一个结构体,而在C#却不能直接把byte数组转换为结构体,要在C#中发送结构体,可以按以下方法实现:
(1)定义结构体:
//命名空间
using System.Runtime.InteropServices;
//注意这个属性不能少
[StructLayoutAttribute(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]
struct TestStruct
...{
public int c;
//字符串,SizeConst为字符串的最大长度
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string str;
//int数组,SizeConst表示数组的个数,在转换成
//byte数组前必须先初始化数组,再使用,初始化
//的数组长度必须和SizeConst一致,例test = new int[6];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public int[] test;
}
(2)结构体转byte数组:
/** <summary>
/// 结构体转byte数组
/// </summary>
/// <param name="structObj">要转换的
C#结构体中数组的分配
于 2014-03-19 20:54:20 首次发布