c# - 在 C# 中通过 TCP 发送 C 结构

标签 c# c tcp memcpy

我正在编写一个程序,通过 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/

相关文章:

c# - 标签页添加用户控件

python - 在 Windows 上构建 pHash 库

c - 如何计算数组的最小值、最大值、平均值?

python - 为什么我的 TCP 数据包看起来不像协议(protocol)分析器的 TCP 数据包?

c# - 使用数据库日期时间

c# - 具有关系的简单 ORM

c# - 在 C# 中找出文件所有者/创建者

c - 双指针 vs 单指针

ssl - 当服务器是 https 时,有没有办法查看发送的数据?

c++ - 如何通过 boost asio 支持 TCP 服务器中的多个连接