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

耗尽温柔 提交于 2019-12-10 14:14:20

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7502644/how-to-turn-boostasio-socket-into-c-cli-net-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!