C ++サーバーは次のような構造体をC#クライアントに送信します。
typedef struct {
int cmd; //commend of order
int state; //the state of communication
int step; //the step
int dataLength; //data length
char data[DATA_SIZE];//data
} Message;
C#クライアントを使用して構造体を受信し、メンバーとデータにアクセスしたいのですが、どうすればよいですか?
私はこの問題を解決しました、私はこのようにc#で構造体を定義します:
[StructLayout(LayoutKind.Sequential,Pack =1), Serializable]
struct Message
{
public int cmd;
public int state;
public int step;
public int dataLength;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string ip_segment;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
public byte[] data;
}
バイト配列を受け取ったら、次のようにメッセージに変換します。
public object BytesToStruct(byte[] bytes, Type type)
{
//get the size of Message
int size = Marshal.SizeOf(type);
if (size > bytes.Length)
{
return null;
}
//allocate Message object space
IntPtr structPtr = Marshal.AllocHGlobal(size);
//copy the byte array to the space
Marshal.Copy(bytes, 0, structPtr, size);
//convert byte array to struct Message
object obj = Marshal.PtrToStructure(structPtr, type);
//free the space
Marshal.FreeHGlobal(structPtr);
//return object
return obj;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加