How to call C ++ DLL in C #

I wrote a DLL in dev C ++. The DLL name is "DllMain.dll" and contains two functions: HelloWorld and ShowMe . The header file is as follows:

 DLLIMPORT void HelloWorld(); DLLIMPORT void ShowMe(); 

And the source file is as follows:

 DLLIMPORT void HelloWorld () { MessageBox (0, "Hello World from DLL!\n", "Hi",MB_ICONINFORMATION); } DLLIMPORT void ShowMe() { MessageBox (0, "How are u?", "Hi", MB_ICONINFORMATION); } 

I compile the code in a DLL and call two functions from C #. C # code is as follows:

 [DllImport("DllMain.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void HelloWorld(); [DllImport("DllMain.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void ShowMe(); 

When I call the "HelloWorld" function, it works well and a messageBox pops up, but when I call the ShowMe function, an EntryPointNotFoundException . How to avoid this exception? Do I need to add extern "C" to the header file?

+6
source share
3 answers

The following code in VS 2012 worked perfectly:

 #include <Windows.h> extern "C" { __declspec(dllexport) void HelloWorld () { MessageBox (0, L"Hello World from DLL!\n", L"Hi",MB_ICONINFORMATION); } __declspec(dllexport) void ShowMe() { MessageBox (0, L"How are u?", L"Hi", MB_ICONINFORMATION); } } 

NOTE: If I remove extern "C" , I get an exception.

+7
source

things that helped:

  • : extern "C" {function declarations here in the h file} will disable the C ++ name encoding. therefore C # will find a function

  • Use __stdcall to declare C or CallingConvention.Cdecl in a C # declaration

  • it is possible to use BSTR / _bstr_t as a string type and use other vb types. http://support.microsoft.com/kb/177218/EN-US

  • download "PInvoke Interop Assistant" https://clrinterop.codeplex.com/releases/view/14120 insert a function declaration from a .h file on the third tab = C # declaration. replace the dll file name.

+2
source
 using System; using System.Runtime.InteropServices; namespace MyNameSpace { public class MyClass { [DllImport("DllMain.dll", EntryPoint = "HelloWorld")] public static extern void HelloWorld(); [DllImport("DllMain.dll", EntryPoint = "ShowMe")] public static extern void ShowMe(); } } 
+1
source

Source: https://habr.com/ru/post/944104/


All Articles