3

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());
Rella
  • 65,003
  • 109
  • 363
  • 636
  • What exactly wannt you to do? Replace a boost::asio socket by a .NET one? – Simon Sep 09 '11 at 12:44
  • no - I want havicg created and accepted connection on .Net side to turn .Net Socket instance into Boost::asio Socket. – Rella Sep 09 '11 at 12:47
  • What do you mean by "turn .NET Socket into Boost::asio Socket"? Porting at code level? Made a connection via TCP between them? Or? – Simon Sep 09 '11 at 12:52
  • Is there a boost version for .net out? Is there a .net version for c++ out? Else you will probably have to make an interop call. Is the C++ code in a separate dll? Or the .net code? – RedX Sep 09 '11 at 12:59
  • 3
    @Kabumbus: Probably you can use the value of the Handle property of the System::Net::Sockets::Socket class. – Simon Sep 09 '11 at 13:01
  • 1
    @RedX: there is a .NET version for C++ out: it's called C++/CLI and is referred to in the question. Kabumbus: wouldn't it be easier to just open a boost.asio socket directly? – R. Martinho Fernandes Sep 09 '11 at 13:47
  • @Fernandes Didn't know you could use C++/CLI with .Net. Learned something today, thanks. – RedX Sep 09 '11 at 15:19
  • @RedX : C++/CLI can't be used _without_ .Net. – ildjarn Sep 09 '11 at 16:52
  • @ildjam wouldn't that be the same as saying C++ cant be used without STL or boost? – RedX Sep 09 '11 at 19:42
  • @RedX : No, STL and Boost are libraries and thus optional; C++/CLI compiles to MSIL, and consequently **needs** the .Net CLR in order to to execute at all. – ildjarn Sep 09 '11 at 20:21
  • Isn't what I had shown you works? – Artyom Sep 21 '11 at 08:18

2 Answers2

4

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:

Artyom
  • 31,019
  • 21
  • 127
  • 215
  • May be you could provide us with some more full, tested code answer on related topic http://stackoverflow.com/q/7502644/434051 (Asio to .Net) – Rella Sep 23 '11 at 20:59
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.

Community
  • 1
  • 1
David Schwartz
  • 179,497
  • 17
  • 214
  • 278