C# 如何封送包含可变大小字符串的结构?
我通过TCP连接将数据包(C# 如何封送包含可变大小字符串的结构?,c#,tcp,struct,marshalling,unmarshalling,C#,Tcp,Struct,Marshalling,Unmarshalling,我通过TCP连接将数据包(MemoryStream)从客户端发送到服务器,在服务器端,我希望使用封送处理重新创建原始对象。我使用以下代码将内容封送到数据包中: public void Write<T>(T value) where T : struct { byte[] buffer = new byte[Marshal.SizeOf(typeof(T))]; // Fill the buffer with our stuff ple
MemoryStream
)从客户端发送到服务器,在服务器端,我希望使用封送处理重新创建原始对象。我使用以下代码将内容封送到数据包中:
public void Write<T>(T value) where T : struct
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
// Fill the buffer with our stuff please!
fixed (byte* b = buffer)
Marshal.StructureToPtr(value, new IntPtr(b), false);
// And write it to the MemoryStream. Kthx!
Write(buffer, 0, buffer.Length);
}
我通常通过在StructLayout
属性中指定Size
来使这些结构工作。然而,现在我有两个大小不同的字符串,我一辈子都不知道如何让封送器
抓取一个数据包(它是一个字节数组)并让它封送回上面的结构,因为我不能将它指定为LPStr
并设置它的大小-它会有所不同
因此,每当我试图这样做,元帅就会对我大喊大叫,说:
类型“HotspotUpdate”不能作为非托管结构封送;无法计算有意义的大小或偏移量。
有没有什么方法可以让这项工作正常进行,或者我只能通过一个字节数组发送字符串,然后在服务器端进行计算?CLR要求结构成员位于固定偏移量处。因此,不存在大小可变的构件 也许,无论如何,您都应该使用更高级别的抽象。使用协议缓冲区以一种方便而健壮的方式自动化所有序列化需求
[StructLayout(LayoutKind.Sequential)]
public struct HotspotUpdate
{
public string LeaderHash { get; set; }
public string OurName { get; set; }
public CommandSide Side { get; set; }
public CommandType Type { get; set; }
public Vector3 Location { get; set; }
}