接收C#客户端上从C ++服务器发送的数据

时间:2015-10-23 16:43:47

标签: c# c++

C ++服务器会将这样的结构发送到C#client:

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#客户端接收结构并访问成员和数据,我该怎么做?

1 个答案:

答案 0 :(得分:1)

我已经解决了这个问题,我在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;
        }