Calling Unmanaged C++ from C#

荒凉一梦 提交于 2019-12-23 18:34:12

问题


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

  • 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.

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.

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

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.


回答1:


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.

Example from 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);
    }
}


来源:https://stackoverflow.com/questions/18997672/calling-unmanaged-c-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!