结构到字节数组以通过套接字发送

c00*_*0ke 2 .net sockets serialization struct bytearray

从结构中获取字节数组以通过TCP套接字发送的最佳方法是什么?我正在使用.Net(VB或C#).

Gro*_*roo 7

如果您正在使用C#,您也可以自己将其编组为本机缓冲区,以便更好地控制序列化.

您需要在结构中添加适当的属性,

  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack=1)]
Run Code Online (Sandbox Code Playgroud)

然后你可以使用以下命令序列化它:

    /// <summary>
    /// Serializes the specified object into a byte array.
    /// </summary>
    /// <param name="nativeObject">The object to serialize.</param>
    /// <returns></returns>
    public static byte[] Serialize(object obj)
    {
        Type objectType = obj.GetType();
        int objectSize = Marshal.SizeOf(obj);
        IntPtr buffer = Marshal.AllocHGlobal(objectSize);
        Marshal.StructureToPtr(obj, buffer, false);
        byte[] array = new byte[objectSize];
        Marshal.Copy(buffer, array , 0, objectSize);
        Marshal.FreeHGlobal(buffer);
        return array;
    }
Run Code Online (Sandbox Code Playgroud)