在C#中使用来自导入的C ++ dll的事件处理程序

时间:2014-02-21 15:56:36

标签: c# c++ dllimport

我正在使用提供方法和一些事件处理程序的第三方C库。我想订阅一个或多个事件,但我不知道如何在C#中导入C库时如何做到这一点。

方法不是问题。例如,我使用这个

[C++]
    API ResultType DoSometing(DeviceHandle devHndl);

[C#]
    [DllImport("Some.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern ErrorType DoSomething(IntPtr devHndl);

对于这些事件,我有以下定义:

[C++]
typedef ResultType (CALLING_CONVENTION *FPtr_GetStatus)(DeviceHandle);
typedef void (CALLING_CONVENTION *FPtr_DeviceEventHandler)(DeviceHandle devHndl, DeviceEvent event, void *context);
API FPtr_DeviceEventHandler RegisterSomeEventHandler(FPtr_DeviceEventHandler handler, void *context);

如何处理C#代码中的这个?

2 个答案:

答案 0 :(得分:0)

那些事件处理程序实际上是回调函数。所以你必须在C#端使用委托。

这些方面的东西......

delegate ResultType GetStatusDelegate(IntPtr deviceHandle);
delegate void DeviceEventDelegate(IntPtr deviceHandle, DeviceEvent e, IntPtr context);

[DllImport("Some.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void RegisterSomeEventHandler(DeviceEventDelegate handler, IntPtr context);

上面示例中缺少的是ResultTypeDeviceEvent的声明,这些声明在问题中不可用。那些也必须被宣布。

答案 1 :(得分:0)