Triggering event in C# from C++ DLL

末鹿安然 提交于 2020-01-01 03:18:05

问题


I have an umanaged C++ DLL which is communicating with a Cisco Server (UCCX).

It sends and receives messages to and from this server via TCP/IP. Now there are some types of messages it receives which contains some parameters which it needs to send to a C# GUI which will display these parameters on screen.

Please tell me an efficient method to trigger an event in C# from this DLL.


回答1:


http://blogs.msdn.com/b/davidnotario/archive/2006/01/13/512436.aspx seems to answer your question. You use a delegate on the C# side and a standard callback on the C++ side.

C++ side:

typedef void (__stdcall *PFN_MYCALLBACK)();
int __stdcall MyUnmanagedApi(PFN_ MYCALLBACK callback);

C# side

public delegate void MyCallback();
[DllImport("MYDLL.DLL")] public static extern void MyUnmanagedApi(MyCallback callback);

public static void Main()
{
  MyUnmanagedApi(
    delegate()
    {
      Console.WriteLine("Called back by unmanaged side");
    }
   );
}



回答2:


Note the C++ side should be

typedef void (__stdcall *PFN_MYCALLBACK)();
extern "C" __declspec(dllexport) void __stdcall MyUnmanagedApi(PFN_ MYCALLBACK callback);

An alternate option is to drop the __stdcall on the C++ side

typedef void (*PFN_MYCALLBACK)();
extern "C" __declspec(dllexport) void MyUnmanagedApi(PFN_ MYCALLBACK callback);

And on the C# side:

public delegate void MyCallback();
[DllImport("MYDLL.DLL", CallingConvention = CallingConvention.Cdecl))] 
public static extern void MyUnmanagedApi(MyCallback callback);

as above ...


来源:https://stackoverflow.com/questions/12576944/triggering-event-in-c-sharp-from-c-dll

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