5

What I want is simple - code sample of creating new C++/CLI .Net socket from boost asio socket. How to create such thing?

Here is pseudo code of what I would like to do:

.net::socket a;
boost::asio::socket b;
a.assign(b.nativeWin32Socket());

BTW: Here is how to turn C++/CLI .Net socket into boost::asio socket.

Community
  • 1
  • 1
Rella
  • 65,003
  • 109
  • 363
  • 636

2 Answers2

8

You can't 'detach' a Boost.ASIO socket. You can use the native_handle() member function to get a SOCKET handle from the asio::socket object, but you must ensure that the asio::socket object isn't destructed until you're done with the SOCKET. It continues to hold ownership of the native SOCKET and will close it when it's destructor is called.

Like André suggested, you could duplicate the socket handle. However, I wouldn't consider duplicating this socket safe, because Boost.ASIO automatically associates the native SOCKET handle with an I/O completion port. If the .NET Socket wrapper or some other code attempts to associate the duplicated socket with a different I/O completion port, an error will occur. I know that the .NET 2.0 Socket class does, in fact, associate the SOCKET handle with an I/O completion port for asynchronous operations. This may have changed in more recent versions, however.

Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71
  • 2
    Or use [`WSADuplicateSocket`](http://msdn.microsoft.com/en-us/library/ms741565(v=VS.85).aspx), then it doesn't matter when Boost closes the handle, you have an independent handle to the same socket that keeps it open. (Assuming Boost calls `closesocket` and not `shutdown`) – Ben Voigt Sep 21 '11 at 17:22
  • Even if you can't detach the socket, you can still [duplicate the socket handle](http://msdn.microsoft.com/en-us/library/ms741565(v=VS.85).aspx) so that both abstractions can share the same socket through two different handles. – André Caron Sep 21 '11 at 17:23
  • The Boost implementation associates the SOCKET handle with an I/O completion port. I wouldn't consider duplicating this socket safe, unless you're 100% sure there's no chance of some other code trying to associate it with a second I/O completion port; I know that the 2.0 .NET Socket class does use an IOCP internally for async operations, though that may have changed in later versions. – Collin Dauphinee Sep 21 '11 at 19:01
3

You can probably use the PROTOCOL_INFO structure returned by WSADuplicateSocket(), convert it to its SocketInformation equivalent and then use the appropriate socket constructor to get a shared socket with a different handle.

The "Remarks" section in the documentation on WSADuplicateSocket() depicts the usual control flow involved in socket duplication. I think this flow is somewhat equivalent to the SocketInformation Socket::DuplicateAndClose() and Socket(SocketInformation) pair of calls.

André Caron
  • 44,541
  • 12
  • 67
  • 125