Search code examples
c#c++dllimportdllexportdllnotfoundexception

Unable to import c++ dll to c# project using DllImport


I'm trying to import a C++ Project Dll into a C# project. I found a lot of people talk about using DllImport. I tried using that and here is what I have-

CPP Code:

int __declspec(dllexport) beginCode(double reportId);

C# Code:

[DllImport("C:\\Users\\<my_user_id>\\Desktop\\ctxmix\\Release\\ctxmix.dll",CallingConvention =CallingConvention.Cdecl ,CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int beginCode(double reportId);
int result = beginCode(reportId);

But when I run, I'm getting an exception - Exception thrown:

System.DllNotFoundException

Do I have to add any references for the CPP Dll in the project or do anything else apart from the code which I have on the top?

Edit: I'm trying to run my .exe using VS2015 and I get this exception on my local machine. Also, I don't see my CPP Dll in the Project->References section where as I see other references there.


Solution

  • The unmanaged DLL needs to be locateable by your managed process. Typically that means placing the DLL in the same directory as the executable file. But you gave used an absolute path which I presume you transcribed correctly.

    You may also encounter this error if the DLL's dependencies cannot be located. That seems the likely explanation here. Most likely the MSVC runtime cannot be located when your DLL is loaded.

    Using an absolute path isn't a great idea. That will break down when you distribute to another machine. Use just the DLL file name and place it in the same directory as the executable.

    Your DllImport attribute seems fussy. No point specifying CharSet when there is no text. I doubt your function calls SetLastError. And do you really need ExactSpelling?