最近在用C#做一個項目的時候
using System
[Serializable] // 指示可序列化
[StructLayout(LayoutKind
public struct Operator
{
public ushort id;
[MarshalAs(UnmanagedType
public char[] name;
[MarshalAs(UnmanagedType
public char[] pass;
public Operator(string user
{
this
this
this
}
}
C++與C#的數據類型對應關系表
API數據類型
類型描述
C#類型
API數據類型
類型描述
C#類型
WORD
整個結構的字節數是
對應的C++結構體是
typedef struct
{
WORD id;
CHAR name[
CHAR password[
}Operator;
using System
/// <summary>
/// 將結構轉換為字節數組
/// </summary>
/// <param name=
/// <returns>字節數組</returns>
public byte[] StructToBytes(object obj)
{
//得到結構體的大小
int size = Marshal
//創建byte數組
byte[] bytes = new byte[size];
//分配結構體大小的內存空間
IntPtr structPtr = Marshal
//將結構體拷到分配好的內存空間
Marshal
//從內存空間拷到byte數組
Marshal
//釋放內存空間
Marshal
//返回byte數組
return bytes;
}
接收的時候需要把字節數組轉換成結構
/// <summary>
/// byte數組轉結構
/// </summary>
/// <param name=
/// <param name=
/// <returns>轉換後的結構</returns>
public object BytesToStruct(byte[] bytes
{
//得到結構的大小
int size = Marshal
Log(size
//byte數組長度小於結構的大小
if (size > bytes
{
//返回空
return null;
}
//分配結構大小的內存空間
IntPtr structPtr = Marshal
//將byte數組拷到分配好的內存空間
Marshal
//將內存空間轉換為目標結構
object obj = Marshal
//釋放內存空間
Marshal
//返回結構
return obj;
}
using System
using System
using System
using System
byte[] Message = StructToBytes(new Operator(
TcpClient socket = new TcpClient();
socket
NetworkStream ns = Socket
ns
byte[] Recv = new byte[
int NumberOfRecv =
IList<byte> newRecv = new List<byte>();
ns
try
{
do
{
// 接收響應
NumberOfRecv = ns
for (int i =
newRecv
}
while (ns
byte[] resultRecv = new byte[newRecv
newRecv
Operator MyOper = new Operator();
MyOper = (Operator)BytesToStruct(resultRecv
在這裡取值的時候可能會出現只能取到一個字段
Operator
socket
ns
From:http://tw.wingwit.com/Article/program/c/201311/11108.html