Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to turn boost::asio socket into C++/CLI .Net socket?

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.

like image 296
Rella Avatar asked Sep 21 '11 15:09

Rella


2 Answers

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.

like image 84
Collin Dauphinee Avatar answered Oct 05 '22 23:10

Collin Dauphinee


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.

like image 24
André Caron Avatar answered Oct 05 '22 22:10

André Caron