一、c#結(jié)構(gòu)體
1、定義與C++對應(yīng)的C#結(jié)構(gòu)體
在c#中的結(jié)構(gòu)體不能定義指針,不能定義字符數(shù)組,只能在里面定義字符數(shù)組的引用。
C++的消息結(jié)構(gòu)體如下:
//消息格式 4+16+4+4= 28個字節(jié)
struct cs_message
{
u32_t cmd_type;
char username[16];
u32_t dstID;
u32_t srcID;
};
C#定義的結(jié)構(gòu)體如下:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct my_message
{
public UInt32 cmd_type;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string username;
public UInt32 dstID;
public UInt32 srcID;
public my_message(string s)
{
cmd_type = 0;
username = s;
dstID = 0;
srcID = 0;
}
}
在C++的頭文件定義中,使用了 #pragma pack 1 字節(jié)按1對齊,所以C#的結(jié)構(gòu)體也必須要加上對應(yīng)的特
性,LayoutKind.Sequential屬性讓結(jié)構(gòu)體在導(dǎo)出到非托管內(nèi)存時按出現(xiàn)的順序依次布局,而對于C++的
char數(shù)組類型,C#中可以直接使用string來對應(yīng),當(dāng)然了,也要加上封送的特性和長度限制。
2、結(jié)構(gòu)體與byte[]的互相轉(zhuǎn)換
定義一個類,里面有2個方法去實現(xiàn)互轉(zhuǎn):
public class Converter
{
public Byte[] StructToBytes(Object structure)
{
Int32 size = Marshal.SizeOf(structure);
Console.WriteLine(size);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, buffer, false);
Byte[] bytes = new Byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
public Object BytesToStruct(Byte[] bytes, Type strcutType)
{
Int32 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);
}
}
}
3、測試結(jié)果:
static void Main(string[] args)
{
//定義轉(zhuǎn)換類的一個對象并初始化
Converter Convert = new Converter();
//定義消息結(jié)構(gòu)體
my_message m;
//初始化消息結(jié)構(gòu)體
m = new my_message("yanlina");
m.cmd_type = 1633837924;
m.srcID = 1633837924;
m.dstID = 1633837924;
//使用轉(zhuǎn)換類的對象的StructToBytes方法把m結(jié)構(gòu)體轉(zhuǎn)換成Byte
Byte[] message = Convert.StructToBytes(m);
//使用轉(zhuǎn)換類的對象的BytesToStruct方法把Byte轉(zhuǎn)換成m結(jié)構(gòu)體
my_message n = (my_message)Convert.BytesToStruct(message, m.GetType());
//輸出測試
Console.WriteLine(Encoding.ASCII.GetString(message));
Console.WriteLine(n.username);
}
結(jié)構(gòu)體的size是28個字節(jié)和c++的結(jié)構(gòu)體一樣,同時可以將結(jié)構(gòu)體和字節(jié)數(shù)組互轉(zhuǎn),方便UDP的發(fā)送和接收。
本文來自CSDN博客,轉(zhuǎn)載請標(biāo)明出處:
http://blog.csdn.net/huxiangyang4/archive/2010/08/31/5853247.aspx