amichai amichai - 8 months ago 58
C++ Question

using cpp dll in c# code

I'm trying to use native c++ dll inside a c# application.

I followed this article to get started.

Its working fine while the dll using only c files (like in the tutorial), but when using cpp files I cant make it work.

using the dumpbin tool I can see that my exported function names changed.
for example a function call 'next' changed to '?next@@YAHH@Z' and when I'm trying to call it in the c# code it cant find it.

my dll code is:

int next(int n)
return n + 1;

the c# code

[DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int next(int n);

its the same code while using c file or cpp files

Thanks in advance


What you are attempting to do is to make a trampoline function, to externalize the use of your C++ objects.

What you are experiencing is called symbol mangling. It is a c++-specific way of naming the symbols (like the functions) in a dynamic library and an executable.

You have to specify that you want to cancel the mangling effect by using an extern "C" statement in your library code, just like this:

extern "C" __declspec(dllexport)
int next(int n)
    return n + 1;

More on this here: Exporting functions from a DLL with dllexport