从C#调用非托管C ++ [英] Calling Unmanaged C++ from C#

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

问题描述

我正在带有.NET 4.0的Win7上运行VS2012。
我尝试了以下操作:

I'm running VS2012 on Win7 with .NET 4.0. I've tried the following:


  • 创建C ++ DLL项目

  • 已检查\ \未选中导出符号框

  • 我确保平台目标相同。就我而言,win32

  • 我在需要的地方添加了必要的extern C和__declspec(dllexport)。

  • 我已经成功编译了我的DLL并尝试在C#项目中引用它。

  • Create C++ DLL project
  • Checked\Unchecked the export symbols box
  • I've made sure my platform targets are the same. In my case, win32
  • I've added the necessary extern "C" and __declspec(dllexport) where needed.
  • I've successfully compiled my DLL and have tried to reference it in a C# project.

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

Unfortunately, I get an error telling my it can't be added and that I need to make sure it's a valid assembly or COM object.

我已经放弃了尝试导出代码的工作,因此我很满意只是示例 42通过了!

I've given up trying to get my code to export, so I'd be happy with just the example "42" getting through!

我尝试使用dumpbin对其进行查看,它可以正确导出符号:

I've tried looking at it with dumpbin and it is correctly exporting symbols:

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

我的脑子里没有想法。有人可以启发我吗?无论尝试什么,我似乎都会遇到此错误。

My brain is fresh out of ideas. Can someone please enlighten me? I seem to get this error no matter what I try.

推荐答案

您需要调用驻留在C ++ DLL中的函数(已导出)使用 DllImportAttribute 从.NET代码中使用外部 C )。您不能像.NET程序集一样引用C ++ DLL,也不能使用DLL中的类,只能使用 DllImport ed的C类函数。

You need to pinvoke the functions residing in your C++ DLL (exported using extern "C") from your .NET code using the DllImportAttribute. You can't reference your C++ DLL like a .NET assembly, and you can't use classes from the DLL, only DllImported C-like functions.

来自 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);
    }
}

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

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