Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass socket from .NET to unmanaged C++ code

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!

like image 790
Trogvar Avatar asked Apr 13 '11 08:04

Trogvar


2 Answers

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();
        }
    }
}
like image 164
meklarian Avatar answered Nov 11 '22 05:11

meklarian


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

like image 34
ildjarn Avatar answered Nov 11 '22 04:11

ildjarn