将套接字从 .NET 传递到非托管 C++代码

发布于 2024-11-01 03:31:38 字数 120 浏览 3 评论 0原文

我目前有一个 .NET 程序启动与服务器的连接。有时我需要调用特殊的非托管 C++ 代码,它使用与服务器的连接。

如何在非托管 C++ 代码中传递和使用来自 .NET 的套接字连接?

提前致谢!

I currently have a .NET program initiating a connection to a server. Sometimes I need to call a special unmanaged C++ code, which uses the connection to the server.

How to pass and use socket connection from .NET in unmanaged C++ code?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱,才寂寞 2024-11-08 03:31:38

Socket 类具有可以使用的 Handle 属性。

Socket.Handle @ MSDN

我是我对这是否有效持怀疑态度,但我能够毫不费力地让它发挥作用。

首先,我创建了一个非托管 C++ dll 来导出可以使用套接字执行某些操作的单个函数。这是我创建的函数。

#include <WinSock.h>

// This is an example of an exported function.
extern "C" __declspec(dllexport) void __stdcall DoStuffWithSocket(DWORD sock)
{
  const char *data = "woot\r\n";
  send((SOCKET)sock, data, strlen(data), 0);
}

该项目输出一个名为 UnmanagementSocketHandler.dll 的 dll,它是下一个代码片段中的 P/Invoke 签名中提到的库。

这是一个快速但肮脏的 C# 控制台应用程序,用于将该函数作为服务器调用。

using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

namespace SocketHandleShareTest
{
    class Program
    {
        static void Main(string[] args)
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 5353);
            Socket sListen = new Socket(AddressFamily.InterNetwork, 
                                        SocketType.Stream, ProtocolType.Tcp);
            sListen.Bind(ep);
            sListen.Listen(10);
            Socket sClient = sListen.Accept();
            Console.WriteLine("DoStuffWithSocket() enter");
            Console.ReadLine();
            DoStuffWithSocket(sClient.Handle);
            Console.WriteLine("DoStuffWithSocket() exit");
            Console.ReadLine();
            sClient.Close();
            sListen.Close();
            Console.WriteLine("Done.");
            Console.ReadLine();
        }

        [DllImport("UnmanagedSocketHandler.dll")]
        static extern void DoStuffWithSocket(IntPtr sock);
    }
}    

最后,一个快速但肮脏的 C# 客户端应用程序与服务器通信。我无法找到任何有关其工作原理的文档,但它确实有效。我会对你尝试用套接字做的事情保持警惕。

using System.Net;
using System.Net.Sockets;

namespace SocketHandleShareTestClient
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] buf = new byte[40];
            Socket s = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.IP);
            s.Connect("localhost", 5353);
            int len = s.Receive(buf);
            Console.WriteLine("{0} bytes read.", len);
            if (len > 0)
            {
                string data = Encoding.ASCII.GetString(buf, 0, len);
                Console.WriteLine(data);
            }
            s.Close();
            Console.ReadLine();
        }
    }
}

The Socket class has the Handle property, which could be used.

Socket.Handle @ MSDN

I was skeptical about whether this would work, but I was able to get it to work with no fuss at all.

To start, I made an unmanaged C++ dll to export a single function that can do something with a socket. Here's the function I created.

#include <WinSock.h>

// This is an example of an exported function.
extern "C" __declspec(dllexport) void __stdcall DoStuffWithSocket(DWORD sock)
{
  const char *data = "woot\r\n";
  send((SOCKET)sock, data, strlen(data), 0);
}

The project outputs a dll named UnmanagedSocketHandler.dll, which is the library mentioned in the P/Invoke signature in the next snippet.

Here's a quick and dirty C# console app to call that function as a Server.

using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

namespace SocketHandleShareTest
{
    class Program
    {
        static void Main(string[] args)
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 5353);
            Socket sListen = new Socket(AddressFamily.InterNetwork, 
                                        SocketType.Stream, ProtocolType.Tcp);
            sListen.Bind(ep);
            sListen.Listen(10);
            Socket sClient = sListen.Accept();
            Console.WriteLine("DoStuffWithSocket() enter");
            Console.ReadLine();
            DoStuffWithSocket(sClient.Handle);
            Console.WriteLine("DoStuffWithSocket() exit");
            Console.ReadLine();
            sClient.Close();
            sListen.Close();
            Console.WriteLine("Done.");
            Console.ReadLine();
        }

        [DllImport("UnmanagedSocketHandler.dll")]
        static extern void DoStuffWithSocket(IntPtr sock);
    }
}    

Last, a quick and dirty C# client app to talk to the server. I was unable to find any documentation on why this works, but it works. I'd be wary about what you try to do with the socket.

using System.Net;
using System.Net.Sockets;

namespace SocketHandleShareTestClient
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] buf = new byte[40];
            Socket s = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.IP);
            s.Connect("localhost", 5353);
            int len = s.Receive(buf);
            Console.WriteLine("{0} bytes read.", len);
            if (len > 0)
            {
                string data = Encoding.ASCII.GetString(buf, 0, len);
                Console.WriteLine(data);
            }
            s.Close();
            Console.ReadLine();
        }
    }
}
娜些时光,永不杰束 2024-11-08 03:31:38

Socket 意味着System::Net::Sockets::Socket?如果是这样,请传递 Socket::Handle 到非托管代码。

Socket meaning System::Net::Sockets::Socket? If so, pass Socket::Handle to the unmanaged code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文