locked
DllImport and search path in Visual Studio add-in RRS feed

  • Question

  • Hi there,

    This may not be the right forum exactly but I'll try anyway. In my Visual Studio add-in (C#), I need to invoke a method in an unmanaged DLL that's in the same directory as my add-in's DLL. I'm relying on a "DllImport" statement to locate the latter DLL and based on the expected search order that Windows follows to located unmanaged DLLs (the same one documented under "LoadLibrary()", etc.), I wouldn't expect my DLL to be found. It's definitely not in the "LoadLibrary()" search path when my function is called but it's being found anyway. Can someone explain how this could be? I want to make sure my unmanaged DLL is always going to be found. Note BTW that I can't rely on "SetDllDirectory()". That will potentially cause a problem since my app is hosted by Visual Studio ("devenv.exe") so it might trash the same call being made by others in that environment (and testing shows that it can). Explicitly calling "LoadLibrary" is also best avoided if possible (if "DllImport" will do the job). Thanks very much.



    • Edited by Johnn R1 Friday, March 2, 2012 7:03 PM
    Friday, March 2, 2012 6:57 PM

Answers

All replies

  • From a contact on the CLR team (I asked if DllImport followed the normal CLR probing/assembly location logic):

    DllImport has its own separate logic. First it looks in the directory of the caller (i.e. the directory where the assembly declaring the P/Invoke is). Then it just calls LoadLibraryEx and relies on the OS probing paths.

    edit:  Also, a new attribute appears in 4.5:  http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.defaultdllimportsearchpathsattribute.defaultdllimportsearchpathsattribute(v=vs.110).aspx

    Ryan

    Saturday, March 3, 2012 1:21 AM
  • Thanks very much! That's greatly appreciated. I'm going to post your comments in the "Community Comments" section of "DllImportAttribute" in MSDN. Nothing is documented about this behavior and from all the reading I've read, most developers are under the impression that it follows the normal "LoadLibrary[Ex]" search path. Who would have known otherwise (the documentation should really clarify the situation). Thanks again!
    Saturday, March 3, 2012 2:21 AM