简体   繁体   中英

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.

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#.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM