vb.netvisual-c++dlldllnotfoundexception

How load the Dll according to platform


I have a dll for 32bit and 64bit and now I want that my exe call the dll from according to solution platform,means when x64 is set then the dll of 64bit will call.For this I declare a function GetPlatform().

Public Function GetPlateform() As String

    Dim var1 As String
    If (IntPtr.Size = 8) Then
        var1 = hellox64
    Else
        var1 = hello
    End If
    Return var1
End Function

and when the form load this var1 is assign to var and finally.

Public Declare Function function1 Lib "var" (ByVal Id As Integer) As Integer

But When I debug the code "DllNotFoundException" is ocuured. NOTE:The dll is in vc++.


Solution

  • Store your native dlls into subfolders and hint the Library Loader by filling accordingly the PATH process environment variable with the path to the correct version to load.

    For instance, given this tree layout...

    Your_assembly.dll
      |_NativeBinaries
          |_x86
              |_your_native.dll
          |_amd64
              |_your_native.dll
    

    ...and this code (sorry, C#, no VB.Net :-/ )...

    internal static class NativeMethods
    {
        private const string nativeName = "your_native";
    
        static NativeMethods()
        {
            string originalAssemblypath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
    
            string currentArchSubPath = "NativeBinaries/x86";
    
            // Is this a 64 bits process?
            if (IntPtr.Size == 8)
            {
                currentArchSubPath = "NativeBinaries/amd64";
            }
    
            string path = Path.Combine(Path.GetDirectoryName(originalAssemblypath), currentArchSubPath);
    
            const string pathEnvVariable = "PATH";
            Environment.SetEnvironmentVariable(pathEnvVariable,
                String.Format("{0}{1}{2}", path, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable)));
        }
    
        [DllImport(nativeName)]
        public static extern int function1(int param);
    
        [DllImport(nativeName)]
        public static extern int function2(int param);
    }
    

    ...function1 and function2 would be dynamically bound to either the 32 or 64 bits version of the native code, depending on the size of an IntPtr (more on this in this post from Scott Hanselman or this StackOverflow question).

    Note 1: This solution is especially useful when both versions of the dll bear the same name or if you're not willing to duplicate every extern references.

    Note 2: This has already been successfully implemented in LibGit2Sharp.