如何在c#中调用c++ DLL
本文关键字:调用 c++ DLL | 更新日期: 2023-09-27 18:11:51
我在dev c++中编写了一个DLL。DLL的名称是"DllMain.dll",它包含两个函数:HelloWorld
和ShowMe
。头文件看起来像这样:
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"时,它运行良好并弹出一个消息框,但是当我调用函数ShowMe
和EntryPointNotFoundException
发生时。如何避免这种例外?我需要在头文件中添加extern "C"
吗?
以下代码在VS 2012中运行良好:
#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);
}
}
注意:如果我删除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();
}
}
帮助的事情:
-
: extern "C" {h文件中的函数声明}将禁用c++名称编码。c#会找到
-
为C声明或CallingConvention使用__stdcall。在c#声明
-
可能使用BSTR/_bstr_t作为字符串类型,并使用其他vb类型。http://support.microsoft.com/kb/177218/EN-US
-
下载"PInvoke互操作助手"https://clrinterop.codeplex.com/releases/view/14120将.h文件中的函数声明粘贴到第三个TAB = c#中声明。