I try to bind a simple c++ dll shown in http://msdn.microsoft.com/en-us/library/ms235636.aspx in my c# console app, but I get a EntryPointNotFoundException for Add within dll at runtime. My test class is
namespace BindingCppDllExample
{
public class BindingDllClass
{
[DllImport("MathFuncsDll.dll")]
public static extern double Add(double a, double b);
}
public class Program
{
public static void Main(string[] args)
{
double a = 2.3;
double b = 3.8;
double c = BindingDllClass.Add(a, b);
Console.WriteLine(string.Format("{0} + {1} = {2}", a, b, c));
}
}
}
What is not correct?
You could try declaring the functions outside of a class and also exporting them with
extern "C"
:Header:
Implementation:
Calling code:
In cases such as this, you can download Dependency Walker, load your DLL into it and look at the Export Functions list. You can also use DumpBin for this.
By default, function exported from a C++ or C DLL are using Name Decoration (also called Name Mangling).
As said on MSDN:
So decorated name for your
Add
function, for example, will look likeAdd@MyMathFuncs@MathFuncs@@SANNN@Z
.But it is possible to force the C++ compiler to expose undecorated names for C++ functions by enclosing the function, and any function prototypes, within an
extern "C" {…}
block, as Darin Dimitrov suggested.Although if you're going to use a third-party DLL (so you can't modify it) or you just don't want to expose decorated names for some reason, you can specify the function's name explicitly: