我通过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 please!
fixed (byte* b = buffer)
Marshal.StructureToPtr(value, new IntPtr(b), false);
// And write it to the MemoryStream. Kthx!
Write(buffer, 0, buffer.Length);
}
当我写完的东西包我呼吁它ToArray()
,并将其发送到服务器。然后服务器将接收一个包含所有数据的字节数组。
这对所有原始类型都适用,但对我的自定义结构不起作用。请看下面的结构我使用的是:
[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; }
}
我通常使这些结构由StructLayout
属性指定Size
工作。然而,现在我有两个字符串在不同的大小,我不能为我的生活弄清楚如何让Marshal
抓住一个数据包(这是一个字节数组),并将其编组回到上面的结构,因为我不能指定它作为LPStr
并设置其大小 - 它会有所不同。
所以每当我试图这样,元帅会冲我嚷嚷,说:
Type 'HotspotUpdate' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
有没有什么办法可以使这项工作,否则我将不得不求助于刚刚发过的字符串一个字节数组并在服务器端处理它们?