amichai
amichai

Reputation: 728

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:

__declspec(dllexport)
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 Amichai

Upvotes: 0

Views: 116

Answers (2)

Christopher J.
Christopher J.

Reputation: 1283

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, to enable polymorphism.

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

Upvotes: 2

Abhishek Kumar
Abhishek Kumar

Reputation: 352

Please provide the Entry Point

An example below

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

Hopefully It helps.

Upvotes: 0

Related Questions