C ++:创建正确类型的回调函数

时间:2017-04-24 18:04:29

标签: c++ dll callback

我正在使用包装器在python中使用硬件组件,使用制造商提供的dll。 DLL附带头文件和lib文件,因此很容易包含dll。 据我所知,通过调用open函数来使用compnent,为一些初始参数提供一个回调函数和一些额外的用户数据,然后调用start方法。在下文中,组件将通过调用回调函数来传递数据。

dll的标题看起来像这样:

#ifndef COMPONENT_DLL_INCLUDED
#define COMPONENT_DLL_INCLUDED

#pragma once

 #ifndef DYNAMIC_COMPONENT_DLL_LINKAGE

  // to allow include in C- and C++-code
  #ifndef DLL_DECLSPEC
   #ifdef __cplusplus
     #define DLL_DECLSPEC  extern "C" __declspec(dllimport)
   #else
     #define DLL_DECLSPEC  __declspec(dllimport)
   #endif
  #endif

typedef struct{
    eInformationType   type;
    eResultType        error;
    ComponentInfo      info;
}AsyncInfo;

typedef struct{                      
    BOOL         someParameter; 
    BOOL         someParameter2;
} ParamSet1;

typedef enum eType {
  UndefinedType   = 0x0,       
  Type1           = 0x1,        
  Type2           = 0x2         
} Param2;


// exported type SendAsynInformation
typedef void ( CALLBACK *SendAsyncInformation )( const AsyncInfo&, void *userInfo);

// exported functions
  DLL_DECLSPEC  eResultType COMPONENT_Open( const ParamSet1 Set1, const Param2 P2, SendAsyncInformation SendAsyncInfo, void *userInfo );
  DLL_DECLSPEC  eResultType COMPONENT_Start( void );

我的问题是,我的回调功能必须如何?我试过像

这样的东西
void myCallback(AsyncInfo *Info, myGlobals *g)
{
    ...something...
}

然后将此回调传递给open函数:

COMPONENT_Open(mySet1, myP2, myCallback, myVoidPtr);

但我总是得到错误:

...cannot convert argument 3 from 'void (__cdecl *)(AsyncInfo *,myGlobals *)' to 'SendAsyncInformation'

我对C ++很陌生,所以很可能这是一个微不足道的问题。我尝试过很多东西,但我不知道该怎么做。那么,我的错误是什么?

1 个答案:

答案 0 :(得分:1)

您需要将myCallback定义为

void CALLBACK myCallback(const AsyncInfo&, void *userInfo)
{ ... }

并将COMPONENT_Open称为

COMPONENT_Open(mySet1, myP2, (SendAsyncInformation)&myCallback, myVoidPtr);

函数原型中的CALLBACK关键字(或实际上的宏)规定了编译器假设使用的调用约定,如果不匹配则可以在堆栈帧清理时给出异常。

由于COMPONENT_Open函数接受回调作为SendAsyncInformation类型typedef,因此您需要将myCallback的地址转换为{{1} }}