如何从C#函数传递Win32 Dll api的回调参数?

时间:2015-01-13 10:26:39

标签: c#

  1. WIN32函数从C#调用:

    int PTSetGUICallbacks (  
      IN int hConnection,
      IN void *pGuiStreamingCallbackCtx,
      IN PT_GUI_STATE_CALLBACK pfnGuiStateCallback,
      IN void *pGuiStateCallbackCtx
    )
    
  2. Win32回调函数原型“PT_GUI_STATE_CALLBACK”:

    int PT_STD_GUI_STATE_CALLBACK (
      IN DWORD dwGuiState,
      OUT BYTE *pbyResponse,
      IN DWORD dwMessage
    )
    
  3. 我调用上面的Win32函数的C#函数我将C#函数作为对Win32函数的回调传递:

    public void SetCallback() 
    {
      var callback_delegate = new PT_GUI_STATE_CALLBACK(GUI_STATE_CALLBACK);            
      GCHandle gch = GCHandle.Alloc(callback_delegate);
      IntPtr intptr_delegate =
        Marshal.GetFunctionPointerForDelegate(callback_delegate);       
      int mErrorCode = PTSetGUICallbacks(mDevHandle, IntPtr.Zero, intptr_delegate,  IntPtr.Zero);       
      gch.Free(); 
     }
    
  4. 这段代码不起作用,我的意思是我没有从win32 api回调到我的C#方法(GUI_STATE_CALLBACK

    所以现在我需要将该回调从我的C#函数传递给win32 api。

    有人知道答案吗?

    1. WIN32 api的PInvoke函数声明:

      public static extern int PTSetGUICallbacks(int ahConnection,
           IntPtr aStreamingcbCtx,IntPtr aGuiStateCb,IntPtr aGuiStateCbCtx);

    2. 对此有何更新?

      还有其他替代方法吗?

1 个答案:

答案 0 :(得分:1)

将您的CallBack功能定义为" CallBack"

public static extern int PTSetGUICallbacks(
int ahConnection,IntPtr aStreamingcbCtx, 
CallBack aGuiStateCb, IntPtr aGuiStateCbCtx);

致电:

CallBack cb = new CallBack(GuiCBFunction);
PTSetGUICallbacks(mDevHandle, IntPtr.Zero, cb,  IntPtr.Zero);

c#中的回调:

int GuiCBFunction (UInt32 dwGuiState, IntPtr pbyResponse, UInt32 dwMessage )
" CallBack":http://msdn.microsoft.com/de-de/library/a95009h1%28v=vs.80%29.aspx

的示例