3

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.

Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
Joseph
  • 63
  • 1
  • 11
  • Sorry about the formatting. Never done this before. I don't know why the editor didn't like my indentations :( – Joseph Sep 25 '13 at 06:25
  • Thanks for the edit, paqogomez! – Joseph Sep 25 '13 at 06:30
  • One common approach is to have C++/CLI (managed C++) "glue" project that can be directly referenced by a C# project. In that managed C++ project, you can call the functions of your native DLL. – cdoubleplusgood Sep 25 '13 at 06:54
  • I had some similar issue a long time ago. By using Dependency Walker i figured out, that the functions weren't exported. I really had to add a *.def file which contained all the exported functions. From this point on, the methods were visible in Dependency Walker and the DllImport worked fine – AcidJunkie Oct 16 '13 at 12:33

1 Answers1

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);
    }
}
gotopie
  • 2,594
  • 1
  • 20
  • 23
  • I've now tried this method, but it claims it can't find the entry point for my test function. And again, I've verified that I'm exporting the functions properly using dumpbin. Everything is public and static of course. I've even put a copy of the DLL in my build folder. – Joseph Sep 28 '13 at 05:49