简体   繁体   中英

How to call C++ DLL in C#

I have written a DLL in dev C++. The DLL's name is "DllMain.dll" and it contains two functions: HelloWorld and ShowMe . The header file looks like this:

DLLIMPORT  void HelloWorld();
DLLIMPORT void ShowMe();

And the source file looks like this:

DLLIMPORT void HelloWorld ()
{
  MessageBox (0, "Hello World from DLL!\n", "Hi",MB_ICONINFORMATION);
}

DLLIMPORT void ShowMe()
{
 MessageBox (0, "How are u?", "Hi", MB_ICONINFORMATION);
}

I compile the code into a DLL and call the two functions from C#. The C# code looks like this:

[DllImport("DllMain.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void HelloWorld();

[DllImport("DllMain.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void ShowMe();

When I call the function "HelloWorld" it runs well and pops up a messageBox, but when I call the function ShowMe an EntryPointNotFoundException occurs. How do I avoid this exception? Do I need to add extern "C" in the header file?

The following code in VS 2012 worked fine:

#include <Windows.h>
extern "C"
{
    __declspec(dllexport) void HelloWorld ()
    {
        MessageBox (0, L"Hello World from DLL!\n", L"Hi",MB_ICONINFORMATION);
    }
    __declspec(dllexport) void ShowMe()
    {
        MessageBox (0, L"How are u?", L"Hi", MB_ICONINFORMATION);
    }
}

NOTE: If I remove the extern "C" I get exception.

using System;
using System.Runtime.InteropServices;

namespace MyNameSpace
{
    public class MyClass
    {
        [DllImport("DllMain.dll", EntryPoint = "HelloWorld")]
        public static extern void HelloWorld();

        [DllImport("DllMain.dll", EntryPoint = "ShowMe")]
        public static extern void ShowMe();
    }
}

things that helped:

  • The: extern "C" { function declarations here in h file } will disable C++ name encoding. so c# will find the function

  • Use __stdcall for the C declaration or CallingConvention.Cdecl in the C# declaration

  • maybe use BSTR/_bstr_t as string type and use other vb types. http://support.microsoft.com/kb/177218/EN-US

  • download "PInvoke Interop Assistant" https://clrinterop.codeplex.com/releases/view/14120 paste function declaration from .h file in the 3rd tab = c# declaration. replace with dll filename.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM