سؤال

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.

هل كانت مفيدة؟

المحلول

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);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top