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

标签 c# c++

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;
        }

关于c# - 在 C# 客户端上接收从 C++ 服务器发送的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307497/

相关文章:

c++ - 如何使 QTabWidget 中的选项卡拉伸(stretch)以避免滚动

c# - SortedList<K ,V> 上是否有 Lower Bound 函数?

c# - 基类和派生类中的链接方法

c++ - directX 11 比例纹理 2D

c++ - 排序 QtTableModel - QTableView 没有得到更新

c++ - _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) 错误

c# - 动态更改 Winforms ComboBox 中项目的文本

c# - 单击按钮更新

c# - 用于在 Unity3D 中定位 3D 对象的 OpenCV 旋转(Rodrigues)和平移向量

c++ - C:使用 strtol endptr 永远不会为 NULL,无法检查值是否仅为整数?