当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Unable to load dll

问题描述:

I am trying to load a dll using DllImport, it works fine if I specified the path of the dll, however, if I do not specified the path of the dll, and just type "foo.dll", it complains "Unable to load dll" even thou I have put the dll file into the bin folder already.

I thought if I do not specified the dll path, it will assume that it will start the dll in the same folder as the exe file, but it seems like it is not the case.

Any suggestion?

Thanks

网友答案:

If you dont want to use a path you could always place the dll in the Windows GAC (wiki link). It can be a pain to do as sometimes you need to sign your dll but means in can be accessed without the path.

网友答案:

Most probably the DLL you are trying to load depends on other resources. You can trick the DllImport by first calling the Win32's LoadLibrary on the remote path. DllImport will notice that the library has already been loaded into memory and it should just work.

The code snippet:

    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("yourlibrary.dll")]
    public static extern void Foo();

    public void CallTheFooMethod()
    {
       // first load the library
       LoadLibrary( "C:/..........full path/yourlibrary.dll" );

       Foo();  
    }
网友答案:

In your C++ dll project open the project properties, navigate to C/C++ -> Code Generation. Then for runtime library set Multi-threaded Debug (/MTd) for Debug configuration and Multi-threaded (/MT) for Release. After that you may put compiled dll in your output directory and check if that works. Feel free to comment and ask questions.

UPD:

Here is the link to the simple little project, which measures current CPU frequency using native code, DllImport'ed to the C# project code.

Steps to build: 1. Build C++ project in any configuration (actually it is not important what configuration to use in this sample). 2. Find compiled dll in the configuration output folder (Debug|Release) 3. Add found dll to the ExternalLibraries folder in the C# project, set action to Copy If Newest in the file Properties (right click on a lib -> Properties). 4. Build and Run C# project -> profit.

Why I suggested this to you: my client asked for a code which will measure CPU frequency, I've ran this code just fine on my machine, but the client didn't. It was dependent on MS VC runtime libs. After setting Multi-threaded Debug (/MTd) for Debug configuration and Multi-threaded (/MT) for Release code of all dependencies becomes embedded in your binary, therefore at least one source of dependencies you can resolve already.

分享给朋友:
您可能感兴趣的文章:
随机阅读: