动态 P/调用 DLL
从 .NET 动态 P/Invoke 非托管代码的最佳方法是什么?
例如,我有许多非托管 DLL,它们之间具有常见的 C 风格导出。 我想获取 DLL 的路径,然后根据导出的名称 P/Invoke 函数。 直到运行时我才知道 DLL 名称。
基本上,.NET 的 LoadLibrary
和 GetProcAddress
等价物是什么? (我现有的代码使用这些函数来完成相同的目标,完全是非托管代码)。
What is the best way to dynamically P/Invoke unmanaged code from .NET?
For example, I have a number of unmanaged DLL's with common C-style exports between them. I would like to take the path to a DLL and then P/Invoke a function based on the exported name. I would not know the DLL name until runtime.
Basically, what is the equivalent of LoadLibrary
and GetProcAddress
for .NET? (I have existing code which uses these functions to accomplish the same goal, entirely in unmanaged code).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
本文介绍了 GetProcAddress 的类型安全托管包装器,应该可以帮助您。
https://learn. microsoft.com/en-us/archive/blogs/jmstall/type-safe-management-wrappers-for-kernel32getprocaddress
This article describes a typesafe managed wrapper for GetProcAddress that should help you out.
https://learn.microsoft.com/en-us/archive/blogs/jmstall/type-safe-managed-wrappers-for-kernel32getprocaddress
您可以通过 P/Invoking LoadLibrary 和 GetProcAddress,然后使用 Marshal.GetDelegateForFunctionPointer。
有关详细信息,请参阅本文。
You can do this by P/Invoking into LoadLibrary and GetProcAddress, and then using Marshal.GetDelegateForFunctionPointer.
For details, see this article.
另请参阅 这篇来自 Jonathan Swift 的博客文章标题为从 .net 动态调用非托管 dll
Also see this blog post from Jonathan Swift title Dynamically calling an unmanaged dll from .net
您可以选择的一种选择是创建一个本机函数,该函数负责将适当的 DLL 和函数加载到内存中,然后根据您的路径将该函数返回到托管代码。 这样你就可以自然地使用 GetProcAddress 技巧并返回函数点。 然后,您可以 PInvoke 进入此函数并返回一个 Delegate,然后该 Delegate 将调用到正确的 DLL。
One option you have is to create a native function which is responsible for loading the appropriate DLL and function into memory and then returning that function to managed code based on your path. This way you can use the GetProcAddress trick naturally and return the function point. You can then PInvoke into this function and get back a Delegate which will then invoke into the proper DLL.