通过TCP在C#中发送C结构 [英] Sending C structs through TCP in C#

查看:120
本文介绍了通过TCP在C#中发送C结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个程序来为通过TCP一台设备的管理界面进行交互。问题是,对于设备的文件是用C语言,而我写程序是在C#。我的问题是,该文件指定

I am writing a program to interact with the management interface for a piece of equipment over TCP. The problem is, the documentation for the equipment is written in C, while the program I am writing is in C#. My problem is, the documentation specifies

的通信是基于该基于C的结构的API缓冲

The communication is based upon the C structure-based API buffer

谷歌搜索再多也似乎指向我这个API或如何我通过TCP发送的原始结构。文档似乎暗示我应该使用的memcpy的结构复制到TCP缓冲区,但C#不直接支持的memcpy。有没有在C#中equivelant方法或不同的方式来做到这一点。

No amount of Googling can seem to point me to this API or how I send a raw structure across TCP. The documentation seems to imply that I should use memcpy to copy the struct to the TCP buffer, but C# doesn't directly support memcpy. Is there an equivelant method in C# or a different way to accomplish this

推荐答案

您可以建立自己的C结构的.NET版本,然后在编组通过网络发送一个字节数组。下面是与 MLocation C结构的例子。

You could build a .Net version of your C struct, then use marshalling to send a byte array through the network. Here's an example with the MLocation C struct.

[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();
}

这篇关于通过TCP在C#中发送C结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆