如何在C#中调用C ++ DLL [英] How to call C++ DLL in C#
问题描述
HelloWorld
和 ShowMe
。头文件如下所示: DLLIMPORT void HelloWorld();
DLLIMPORT void ShowMe();
源文件如下所示:
DLLIMPORT void HelloWorld()
{
MessageBox(0,Hello World from DLL!\\\
,Hi,MB_ICONINFORMATION);
}
DLLIMPORT void ShowMe()
{
MessageBox(0,你好吗?,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
an EntryPointNotFoundException
。如何避免这种异常?我需要在头文件中添加 externC
p> VS 2012中的以下代码正常工作:
#include< Windows.h>
externC
{
__declspec(dllexport)void HelloWorld()
{
MessageBox(0,LHello World from DLL!\\\
L MB_ICONINFORMATION);
}
__declspec(dllexport)void ShowMe()
{
MessageBox(0,L你好吗?,LHi,MB_ICONINFORMATION);
}
}
注意:如果我删除 externC
我得到例外。
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?
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.
这篇关于如何在C#中调用C ++ DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!