Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call C++ DLL in C#

Tags:

I have written a DLL in dev C++. The DLL's name is "DllMain.dll" and it contains two functions: HelloWorld and ShowMe. The header file looks like this:

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

And the source file looks like this:

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 into a DLL and call the two functions from C#. The C# code looks like this:

[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 function "HelloWorld" it runs well and pops up a messageBox, but when I call the function ShowMe an EntryPointNotFoundException occurs. How do I avoid this exception? Do I need to add extern "C" in the header file?

like image 328
user1333098 Avatar asked May 02 '13 07:05

user1333098


People also ask

Can I use a C++ DLL in C #?

Yes, it will work. Just make sure you reference the library in your c++ library and link them together.

How do I link a DLL in Visual Studio?

On Windows you do not link with a . dll file directly – you must use the accompanying . lib file instead. To do that go to Project -> Properties -> Configuration Properties -> Linker -> Additional Dependencies and add path to your .


2 Answers

The following code in VS 2012 worked fine:

#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 the extern "C" I get exception.

like image 136
atoMerz Avatar answered Sep 17 '22 07:09

atoMerz


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();     } } 
like image 31
mjb Avatar answered Sep 20 '22 07:09

mjb