问候,
我的项目结构如下:
\- base (C static library)
callbacks.h
callbacks.c
paint_node.c
.
.
* libBase.a
\-app (C++ application)
main.cpp
在 C 库 'base' 中,我已将全局函数指针声明为:
在单头文件中
回调.h
#ifndef CALLBACKS_H_
#define CALLBACKS_H_
extern void (*putPixelCallBack)();
extern void (*putImageCallBack)();
#endif /* CALLBACKS_H_ */
在单个 C 文件中,它们被初始化为
回调.c
#include "callbacks.h"
void (*putPixelCallBack)();
void (*putImageCallBack)();
其他 C 文件访问此回调函数的方式如下:
paint_node.c
#include "callbacks.h"
void paint_node(node *node,int index){
//Call callbackfunction
.
.
putPixelCallBack(node->x,node->y,index);
}
我编译这些 C 文件并生成静态库“libBase.a”
然后在 C++ 应用程序中,
我想将 C++ 实例方法分配给这个全局函数指针:
我做了如下的事情:
在 Sacm.cpp 文件中
#include "Sacm.h"
extern void (*putPixelCallBack)();
extern void (*putImageCallBack)();
void Sacm::doDetection()
{
putPixelCallBack=(void(*)())&paintPixel;
//call somefunctions in 'libBase' C library
}
void Sacm::paintPixel(int x,int y,int index)
{
qpainter.begin(this);
qpainter.drawPoint(x,y);
qpainter.end();
}
但是编译时出现错误:
sacmtest.cpp: In member function ‘void Sacm::doDetection()’: sacmtest.cpp:113: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&Sacm::paintPixel’ sacmtest.cpp:113: error: converting from ‘void (Sacm::)(int, int, int)’ to ‘void ()()’
有什么建议吗?
最佳答案
这在 C++ 常见问题解答中得到了解答,[ 1 ]。这是行不通的,因为指针不与特定的对象实例关联。那里也给出了解决方案,创建一个使用特定对象的全局函数:
Sacm* sacm_global;
void sacm_global_paintPixel(int x,int y,int index)
{
sacm_global->paintPixel(x, y, index);
}
void Sacm::doDetection()
{
putPixelCallBack = &sacm_global_paintPixel;
//call somefunctions in 'libBase' C library
}
您必须以某种方式正确设置全局变量。
关于c++ - 将 C++ 实例方法分配给全局函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37454812/