Demir
Demir

Reputation: 1837

Call C++ method in C# by DllImport

I have following method in my C++ dll and I am trying to call it in my C# application by means p/invoke.

void Graphics::Create(char* Project, char* Connection, int Count, char *_Source[], char *_Destination[], char *_Search[], char *_Replace[], int _Block[])

Signature I use in C# is:

[DllImport("Wincc.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static public extern void Create(IntPtr Project, IntPtr Connection, int Count, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] _Source, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] _Destination, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] _Search, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] _Replace, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4)] int[] _Block);

I get unknown method in C#. Seems my signature is wrong. However I cannot figure it out what is wrong.

Upvotes: 0

Views: 660

Answers (2)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57690

You can not call a C++ function as C++ does not have C linkage. To achieve this add extern "C" before your function.

extern "C" {
    int foo();
}

But it wont work on C++ methods. There is an uglier solution though. But I dont recommend it.

Best approach is to write down a wrapper. Wrap your tasks (only what you need) in C++ only using function. In the function you can call those methods. And then compile it with C linkage. Then you'll be able to call it from C#.

Upvotes: 1

Vahid Farahmand
Vahid Farahmand

Reputation: 2558

Check your DLL with dependency walker, see if you have proper export in your DLL. Try to define your export in YOURDLLNAME.DEF file. Like this:

YOURLLNAME.DEF

EXPORTS Create

Upvotes: 0

Related Questions