How to call C++ DLL in C#

前端 未结 3 496
暗喜
暗喜 2020-11-30 04:53

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 lik

相关标签:
3条回答
  • 2020-11-30 05:24

    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.

    0 讨论(0)
  • 2020-11-30 05:27

    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.

    0 讨论(0)
  • 2020-11-30 05:38
    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题