c00*_*0ke 2 .net sockets serialization struct bytearray
从结构中获取字节数组以通过TCP套接字发送的最佳方法是什么?我正在使用.Net(VB或C#).
如果您正在使用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)
| 归档时间: |
|
| 查看次数: |
4980 次 |
| 最近记录: |