I have an existing app which P/Invokes to a DLL residing in the same directory as the app itself.
Now (due to the fact that Canon produces one of the crappiest API's around) I need to support two versions of this API and determine at run-time which one I should use (old or new). Since the DLLs have the same name (the first one loads other DLLs with same names so just renaming the first one won't help me) I must keep them in different directories.
Hence my question: what options do I have to control what directory the DLL given in a DllImport declaration uses?
I guess I can start out by trying any of these two ideas:
1) Use "SetDllDirectory" to set my desired directory before doing the first P/Invoke and then reset it afterwards.
2) Load the desired DLL manually using "LoadLibraryEx" and hope that that will do the trick.
But are there any more ".NET:ish way" to try out first?
UPDATE: I realize that I can stuff all access to the DLLs in two separate .Net assemblies and then place each one of them in a separate directory with the corresponding API files. Then I can load the proper .Net assembly dynamically and the loading of the correct DLL whould happen automatically. Any reason that shouldn't work?
I can think of one: how would I go about debugging this stuff? It is possible to tell Visual Studio that an assembly (contained in my solution) shall be placed in a subdirectory and debugged from there?
P/Invoke is the technique a programmer can use to access functions in these libraries. Calls to functions within these libraries occur by declaring the signature of the unmanaged function within managed code, which serves as the actual function that can be called like any other managed method.
Safe DLL search mode places the user's current directory later in the search order. Safe DLL search mode is enabled by default. To disable this feature, create the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SafeDllSearchMode registry value and set it to 0.
My condolences, I've seen one of the APIs and it was indeed shockingly bad. The bigger problem is that you'll need to be able to convince Windows to find the DLL. They won't be in your .exe directory so the default won't work. Using SetDllDirectory() would work, using Environment.CurrentDirectory does too. LoadLibrary cannot work, the P/Invoke marshaller will use LoadLibrary itself.
If it is at all an option, you can use different names for the two P/Invoke declarations, using different arguments for the DllImport() constructor and using the EntryPoint attribute. Doesn't sound like that will fly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With