I currently have a .NET program initiating a connection to a server. Sometimes I need to call a special unmanaged C++ code, which uses the connection to the server.
How to pass and use socket connection from .NET in unmanaged C++ code?
Thanks in advance!
The
Socketclass has theHandleproperty, which could be used.Socket.Handle @ MSDN
I was skeptical about whether this would work, but I was able to get it to work with no fuss at all.
To start, I made an unmanaged C++ dll to export a single function that can do something with a socket. Here’s the function I created.
The project outputs a dll named
UnmanagedSocketHandler.dll, which is the library mentioned in the P/Invoke signature in the next snippet.Here’s a quick and dirty C# console app to call that function as a Server.
Last, a quick and dirty C# client app to talk to the server. I was unable to find any documentation on why this works, but it works. I’d be wary about what you try to do with the socket.