How to reference a DLL using DllImport and a variable in the path?

1

I have a problem at the moment of reference a dll using <DllImport> , because in the place where I put the path of dll <DllImport("C:\MinhaDll.dll")> , I would like to use a variable, and it is not possible, it returns the following error: / p>

  

"Error 11 Constant expression is required."

The variable I want to use will contain the path of the dll, so what other method can I use to reference a dll of a specific path created by the user, since I need a fixed path to use DllImport?

    
asked by anonymous 03.06.2015 / 15:03

1 answer

2

I believe this can not be done.

However, you can add a directory to the process DLLs search path by using function AddDllDirectory ", however as this is a recent API, if you are using a version inferior to Windows 8 , you will need to install a patch .

The function signature is:

Imports System.Runtime.InteropServices
'

<DllImport("kernel32", SetLastError:=True, CharSet:=CharSet.Unicode)> _
 Public Function AddDllDirectory(NewDirectory As String) As Integer
 End Function

If you want to modify the default search path, use the SetDllDirectory function.

An article that might be useful to read is Dynamic-Link Library Search Order that mentions:

  

Before the system looks for a DLL, it checks the following:

     
  • If a DLL with the same module name is already loaded into memory, the system uses the DLL loaded, no matter which directory   that you find. The system does not look for the DLL.
  •   
  • If the DLL is in the list of known DLLs for the version of Windows in which the application runs, the system uses its   known DLLs (and DLLs ) depending on the known DLL, if   there is). The system does not look for the DLL .
  •   

To get a list of DLLs    in the current system, see the following registry key:    HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession    ManagerKnownDLLs .

The value SafeDllSearchMode that is stored in the registry is still mentioned below.

  

If SafeDllSearchMode is enabled in WinXP it is disabled   by default , the search order is as follows:

     
  • The directory from which the application was loaded.
  •   
  • The system directory. Use GetSystemDirectory function to get the path of this directory.
  •   
  • The system directory of 16 bits. There is no function that gets the path of this directory, but it is searched.
  •   
  • The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  •   
  • The current directory.
  •   
  • The directories listed in the environment variable PATH .    Note that this does not include the per-application path specified by the App Paths registry key.
  •   
        
    03.06.2015 / 15:42