如何在C#中调用C ++ DLL

我在开发C ++中编写了一个DLL。 DLL的名称是“DllMain.dll”,它包含两个函数: HelloWorldShowMe 。 头文件如下所示:

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

源文件如下所示:

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

我将代码编译成DLL并从C#调用这两个函数。 C#代码如下所示:

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

当我调用函数“HelloWorld”时它运行良好并弹出一个messageBox,但是当我调用函数ShowMe时会发生一个EntryPointNotFoundException 。 我该如何避免这种exception? 我是否需要在头文件中添加extern "C"

VS 2012中的以下代码运行良好:

 #include  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); } } 

注意:如果我删除extern "C"我会得到例外。

 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(); } } 

有帮助的事情: