将套接字从 .NET 传递到非托管 C++代码
我目前有一个 .NET 程序启动与服务器的连接。有时我需要调用特殊的非托管 C++ 代码,它使用与服务器的连接。
如何在非托管 C++ 代码中传递和使用来自 .NET 的套接字连接?
提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Socket
类具有可以使用的Handle
属性。Socket.Handle @ MSDN
我是我对这是否有效持怀疑态度,但我能够毫不费力地让它发挥作用。
首先,我创建了一个非托管 C++ dll 来导出可以使用套接字执行某些操作的单个函数。这是我创建的函数。
该项目输出一个名为
UnmanagementSocketHandler.dll
的 dll,它是下一个代码片段中的 P/Invoke 签名中提到的库。这是一个快速但肮脏的 C# 控制台应用程序,用于将该函数作为服务器调用。
最后,一个快速但肮脏的 C# 客户端应用程序与服务器通信。我无法找到任何有关其工作原理的文档,但它确实有效。我会对你尝试用套接字做的事情保持警惕。
The
Socket
class has theHandle
property, 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.
Socket
意味着System::Net::Sockets::Socket
?如果是这样,请传递Socket::Handle
到非托管代码。Socket
meaningSystem::Net::Sockets::Socket
? If so, passSocket::Handle
to the unmanaged code.