C++:创建正确类型的回调函数
我正在使用由制造商提供的dll在python中使用硬件组件的包装器。该DLL带有头文件和lib文件,因此很容易包含dll。 据我了解,compnent通过调用open函数来使用,给一些初始参数一个回调函数和一些额外的用户数据,然后调用start方法。在下面,组件将通过调用回调函数来传递数据。C++:创建正确类型的回调函数
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++这样最这可能是一个微不足道的问题。我尝试了很多东西,但我不知道如何去做。那么,我的错误是什么?
您需要定义myCallback
为
void CALLBACK myCallback(const AsyncInfo&, void *userInfo)
{ ... }
并调用该函数原型COMPONENT_Open
作为
COMPONENT_Open(mySet1, myP2, (SendAsyncInformation)&myCallback, myVoidPtr);
的CALLBACK
关键字(或宏实际上)决定什么调用约定它假设编译器使用,如果不匹配,可能会在堆栈帧清理时间期间发生异常。
由于COMPONENT_Open
函数接受回调的类型SendAsyncInformation
这是一个typedef
,因此您需要在myCallback
的地址强制转换为SendAsyncInformation
。
就是这样,谢谢! –
'myCallback'与'SendAsyncInformation'具有相同的原型,那么为什么你需要演员? – ssbssa
回答你的问题的重要信息不在这里 - 应该为其中一个头文件中的COMPONENT_Open函数定义 - 回调函数的签名(返回类型和参数类型)必须与库相同正在期待。错误消息告诉你类型不匹配 - 它是你收到的确切错误信息,然后我猜测回调函数可能是'void SendAsynchInfo(void);. –
使用std :: function –
mutex36