从C#调用非托管C ++

时间:2013-09-25 06:24:24

标签: c# c++ .net dllimport dllexport

我正在使用.NET 4.0在Win7上运行VS2012。 我尝试了以下内容:

  • 创建C ++ DLL项目
  • 选中\取消选中导出符号框
  • 我确保我的平台目标是相同的。就我而言,win32
  • 我已根据需要添加了必要的extern“C”和__declspec(dllexport)。
  • 我已经成功编译了我的DLL,并尝试在C#项目中引用它。

不幸的是,我收到一条错误,告诉我无法添加它,并且我需要确保它是一个有效的程序集或COM对象。

我已经放弃了尝试将代码导出,所以我很高兴只有“42”的例子才能通过!

我尝试用dumpbin查看它并正确导出符号:

1    0 00011023 ??0CEvolutionSimulator@@QAE@XZ
2    1 00011127 ??4CEvolutionSimulator@@QAEAAV0@ABV0@@Z
3    2 00011005 ?GetNumber@CEvolutionSimulator@@QAEHXZ
4    3 0001104B ?fnEvolutionSimulator@@YAHXZ
5    4 00017128 ?nEvolutionSimulator@@3HA

我的大脑是新鲜的想法。有人可以赐教吗?无论我尝试什么,我似乎都会收到这个错误。

1 个答案:

答案 0 :(得分:1)

您需要使用extern "C"从.NET代码中解释驻留在C ++ DLL中的函数(使用DllImportAttribute导出)。您不能像.NET程序集那样引用C ++ DLL,也不能使用DLL中的类,只能使用DllImport类似C的函数。

来自msdn的示例:

using System;
using System.Runtime.InteropServices;

class Example
{
    // Use DllImport to import the Win32 MessageBox function.
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

    static void Main()
    {
        // Call the MessageBox function using platform invoke.
        MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
    }
}