Setting dllimport programmatically in C#

后端 未结 9 1952
情话喂你
情话喂你 2020-12-30 11:10

I am using DllImport in my solution.
My problem is that I have two versions of the same DLL one built for 32 bit and another for 64 bit.

They both e

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 11:15

    I prefer to do this by using the LoadLibrary call from kernel32.dll to force a particular DLL to load from a specific path.

    If you name your 32-bit and 64-bit DLLs the same but placed them in different paths, you could then use the following code to load the correct based on the version of Windows you are running. All you need to do is call ExampleDllLoader.LoadDll() BEFORE any code referencing the ccf class is referenced:

    private static class ccf
    {
        [DllImport("myDllName")]
        public static extern int func1();
    }
    
    public static class ExampleDllLoader
    {
        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        private extern static IntPtr LoadLibrary(string librayName);
    
        public static void LoadDll()
        {
            String path;
    
            //IntPtr.Size will be 4 in 32-bit processes, 8 in 64-bit processes 
            if (IntPtr.Size == 4)
                path = "c:/example32bitpath/myDllName.dll";
            else
                path = "c:/example64bitpath/myDllName.dll";
    
            LoadLibrary(path);
        }
    }
    

提交回复
热议问题