问题
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