Mine_Stone
Mine_Stone

Reputation: 189

Why can't my C# application load my C++ dll?

I want to use C++ code in a C# application, so I wrote a DLL in C++. Because it's the first time that I create a C++ DLL, I started by creating a 'test' dll. Here's the code

extern "C"
{
    __declspec(dllexport) void DisplayHelloFromDLL()
    {
        printf("Hello from DLL !\n");
    }
}

Than I made a very simple C# application:

class DllTest {
    [DllImport("Test.dll")]
    public static extern void DisplayHelloFromDLL();

    public static void UseDll() {
        DisplayHelloFromDLL();
    }
}

After, I built both applications and moved the executable and the dll in the same folder. But when I ran the executable, it showed the following message:

Unhandled exception: System.DllNotFoundException: Unable to load DLL 'Test.dll': The specified module could not be found

Upvotes: 0

Views: 998

Answers (2)

Hiran
Hiran

Reputation: 1180

you need to store the DLL in debug folder. and try this command to check that method is exported properly

dumpbin /exports Test.dll

Upvotes: 1

Pascal
Pascal

Reputation: 142

you have to check the target platform of both dll and exe.

Edit: When Target are different the exception is BadImageFormatException

You will have the DllNotFoundException when the dll or one of its dependencies is not found.

For example, when you compile a debug version of the DLL with VisualStudio, it needs the debug runtimes (which are not installed on machine without the IDE).

you can check your dll dependencies using the Dependency Walker

This tools will also helps you to see the targetted system (x86/x64) and the exported functions (use it on the dll, the program will not show you the [DllImport] dependencies)

Upvotes: 0

Related Questions