如何在 C# 中调用 C++ DLL [英] How to call C++ DLL in C#

查看:28
本文介绍了如何在 C# 中调用 C++ DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 dev C++ 编写了一个 DLL.DLL 的名称是DllMain.dll",它包含两个函数:HelloWorldShowMe.头文件如下所示:

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

源文件如下所示:

DLLIMPORT void HelloWorld ()
{
  MessageBox (0, "Hello World from DLL!
", "Hi",MB_ICONINFORMATION);
}

DLLIMPORT void ShowMe()
{
 MessageBox (0, "How are u?", "Hi", MB_ICONINFORMATION);
}

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

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

当我调用函数HelloWorld"时,它运行良好并弹出一个消息框,但是当我调用函数ShowMe 时,发生EntryPointNotFoundException.如何避免此异常?我需要在头文件中添加 extern "C" 吗?

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?

推荐答案

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

The following code in VS 2012 worked fine:

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

注意:如果我删除 extern "C" 我会得到异常.

NOTE: If I remove the extern "C" I get exception.

这篇关于如何在 C# 中调用 C++ DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆