因為程序必須要和C++開發的程序通信,而通信數據的是結構體的轉化後的字節流,那麼就要求C#能夠順利的將字節流轉換為C#結構體。
代碼
//C++結構體
struct tagCheakUser
{
char userName[12];
char pwd[32];
}
//對應的C#結構體
[StructLayout( LayoutKind.Sequential,Pack=1)]
public struct CheckUser
{
[MarshalAs( UnmanagedType.ByValTStr,SizeConst=12)]
public string userName;
[MarshalAs(UnmanagedType .ByValTStr,SizeConst=32)]
public string pwd;
}
代碼
//convert structure T to byte[]
public static byte[] ConvertStructToBytes(object objStruct)
{
//get the size of structure
int size = Marshal.SizeOf(objStruct);
//define buffer arrays
byte[] buffer = new byte[size];
//Alloc unmanaged memory and Copy structure to unmanaged memory
IntPtr ipStruct = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(objStruct, ipStruct, false);
//Copy to the byte array
Marshal.Copy(ipStruct, buffer, 0, size);
//Free unmanaged memory
Marshal.FreeHGlobal(ipStruct);
return buffer;
}
//convert byte array to sturcture
public static TR ConvertBytesToSturct<TR>(byte[] datas)
{
//get size of sturcture
int size = Marshal.SizeOf(typeof(TR));
//can not be convert
if (datas.Length < size)
{
return