我正在编写一个程序,通过 TCP 与一台设备的管理界面进行交互。问题是,设备的文档是用C写的,而我写的程序是用C#写的。我的问题是,文档指定
The communication is based upon the C structure-based API buffer
再多的谷歌搜索似乎都无法将我指向此 API 或我如何通过 TCP 发送原始结构。文档似乎暗示我应该使用 memcpy 将结构复制到 TCP 缓冲区,但 C# 不直接支持 memcpy。 C# 中是否有等效的方法或不同的方法来完成此操作
最佳答案
您可以构建 C 结构的 .Net 版本,然后使用编码通过网络发送字节数组。下面是 MLocation
C 结构的示例。
[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct MLocation
{
public int x;
public int y;
};
public static void Main()
{
MLocation test = new MLocation();
// Gets size of struct in bytes
int structureSize = Marshal.SizeOf(test);
// Builds byte array
byte[] byteArray = new byte[structureSize];
IntPtr memPtr = IntPtr.Zero;
try
{
// Allocate some unmanaged memory
memPtr = Marshal.AllocHGlobal(structureSize);
// Copy struct to unmanaged memory
Marshal.StructureToPtr(test, memPtr, true);
// Copies to byte array
Marshal.Copy(memPtr, byteArray, 0, structureSize);
}
finally
{
if (memPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(memPtr);
}
}
// Now you can send your byte array through TCP
using (TcpClient client = new TcpClient("host", 8080))
{
using (NetworkStream stream = client.GetStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
}
Console.ReadLine();
}
关于c# - 在 C# 中通过 TCP 发送 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11954431/