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

2019-05-10 11:37发布

问题:

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

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

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

回答1:

Have you tried?

b.assign(a.Handle.ToInt32());

Also note they you will need to use WSADuplicateSocket as you may get that both b and a will close the socket and point you don't expect.

So you need something like:

 SOCKET native = WSADuplicateSocket(a.Handle.ToInt32(),...);
 b.assign(native);

Full Answer (Tested)

SOCKET native = a->Handle.ToInt32();
// Now native is a real socket
b.assign(boost::asio::ip::tcp::v4(), native);

Now it is good idea to duplicate the socket using WSADuplicateSocket:



回答2:

You can use assign to assign a native socket to a Boost asio socket. See the accepted answer to How to create a Boost.Asio socket from a native socket.