P/Invoking to Native DLL with Runtime Filename

我是研究僧i 提交于 2019-12-02 06:51:08

问题


For versioning reasons it would be beneficial for me to be able to use p/invoke on a native C++ dll whose filename will be determined at runtime, as such:

[DllImport(myDllFilename)]
private static extern void MyInvokedMethod();

Unfortunately [DllImport] is an attribute and demands a constant expression. Are there any other options for getting around this error?

I am aware I can use identically named files in different folders and load the right one at runtime, but being able to use differently named files would be ideal for my case.


回答1:


To achieve what you want you need to PInvoke several things (LoadLibrary and GetProcAddress - see links below)... it is called "late binding native code"... using this is not easy/recommended but it is possible...

Some relevant links with explanations, samples and source code:

  • http://blogs.msdn.com/b/junfeng/archive/2004/07/14/181932.aspx
  • http://www.codeproject.com/KB/cs/dyninvok.aspx
  • http://pinvoke.net/default.aspx/kernel32/GetPRocAddress.html
  • http://www.pinvoke.net/default.aspx/kernel32.loadlibrary



回答2:


There is no workaround. You will need to use LoadLibrary and GetProcAddress. That's really no fun at all so I'd try to avoid going that way if feasible.



来源:https://stackoverflow.com/questions/10367641/p-invoking-to-native-dll-with-runtime-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!