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!
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();
        }
    }
}
                        Socket meaning System::Net::Sockets::Socket? If so, pass Socket::Handle to the unmanaged code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With