How to use the custom VC ++ DLL in C #


I am trying to use a custom VC++ dll in my c# project. For doing so I followed this article to create a custom. I was able to create a DLL, link and call in another c++ project (MyExecRefsDLL.vcxproj).

Now, my intention was to use the same DLL in C# code. Therefore, I created another C# console project and tried to add reference (By right click -> Add Reference -> select project "MathFuncDLL") the dll as suggested in above link. I received an error saying - "A reference to 'MathFuncDLL' could not be added".

To overcome this issue I tried to create another project for VC++ dll i.e. MathFuncDLL2 using a project template -> Visual C++ -> Class Library. This time I am able to reference the project in C#. Now at run time I get an error while calling a method from DLL - "EnteryPointNotFoundException was unhandled" "Unable to find an entry point named 'Add' in DLL 'MathFuncDLL2.dll'."

I've created a sample that can be downloaded from this link.

Any help would be highly appreciated.

Your problem might be that C++ decorates function names when exporting. Therefore, Add, might actually be @Add34ZZ.

When running dumpbin /exports MathFuncsDLL2.dll, here is what is returned :

    ordinal hint RVA      name

          1    0 00001193 [email protected]@[email protected]@[email protected] = [email protected]
@[email protected]@[email protected] (public: static double __cdecl MathFuncs::MyMathFuncs::Add(d
          2    1 000011A5 [email protected]@[email protected]@[email protected] = [email protected]
[email protected]@@[email protected] (public: static double __cdecl MathFuncs::MyMathFuncs:
          3    2 0000119F [email protected]@[email protected]@[email protected] = [email protected]
[email protected]@@[email protected] (public: static double __cdecl MathFuncs::MyMathFu
          4    3 00001199 [email protected]@[email protected]@[email protected] = [email protected]
[email protected]@@[email protected] (public: static double __cdecl MathFuncs::MyMathFu

So, the available solutions are :

  • Declare your functions as extern "C" __declspec(dllexport) (and drop the namespaces)

  • Run dumpbin when you compile and use [DllImport("Math.dll", EntryPoint="[email protected]@[email protected]@[email protected]")] If you do this, change you DllImport declaration to [DllImport("MathFuncDLL2.dll", EntryPoint="<functionName>", CallingConvention=CallingConvention.Cdecl)]. The good news is : The call works. The bad new is : it seems to return a pointer to the result.