c# - 无法通过 tcp 在结构中发送字符串变量
问题描述
我在服务器和客户端上有结构:
[StructLayout(LayoutKind.Explicit)]
public struct ObserverStrings
{
[FieldOffset(0)]
public int id;
[FieldOffset(8)]
public string info;
}
通过 id 我了解收到了哪些信息。
在客户端,我发送 id = -3 的信息
ObserverStrings observerStrings = new ObserverStrings {
id = -3,
info = "This is info"
};
byte[] data = WriteStruct(observerStrings);
stream.Write(dota, 0, data.Length);
在服务器上我收到它
ObserverStrings os = ReadStruct<ObserverStrings>(RecievedData, 0, bytes);
public T ReadStruct<T>(byte[] buffer, int index, int count)
{
byte[] tempBuffer = new byte[count];
for (int i = 0; i < count; i++) {
tempBuffer[i] = buffer[index + i];
}
GCHandle handle = GCHandle.Alloc(tempBuffer, GCHandleType.Pinned);
T temp = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return temp;
}
在此之后,我得到“尝试读取或写入受保护的内存。这通常表明其他内存已损坏”或 id = -3 以及一些与我发送的字符串相距甚远的字符串。
我也试过:
StringBuilder builder = new StringBuilder();
builder.Append(Encoding.Unicode.GetString(Measure, 8, bytes - 8));
string[] mesInfo = builder.ToString();
但也得到 id = -3 和一些离我发送的字符串很远的字符串。
解决方案
推荐阅读
- c# - WPFToastNotification 点击事件
- python - mypy 可以检查文档字符串吗?
- python - Tensorflow 仅将 softmax 函数应用于过滤器
- isabelle - Isabelle:数据类型的补充
- visual-c++ - 将字符串转换为 ASCII C++
- javascript - 登录后重定向不正确 - Spring Boot
- c++ - 查找数组中哪一行的平均温度最高
- javascript - 如何让我的文本出现在我的滑块顶部?
- amazon-web-services - AWS chmod 400 pem:没有这样的文件或目录问题
- javascript - 一旦屏幕通过特定点或 jsx 标签,如何获取滚动事件?