Ash*_*iya 3 c c++ pointers function-pointers global-variables
问候,
我的项目结构如下:
\- base (C static library)
callbacks.h
callbacks.c
paint_node.c
.
.
* libBase.a
\-app (C++ application)
main.cpp
Run Code Online (Sandbox Code Playgroud)
在C库'base'中,我将global-function-pointer声明为:
在单头文件中
callbacks.h
#ifndef CALLBACKS_H_
#define CALLBACKS_H_
extern void (*putPixelCallBack)();
extern void (*putImageCallBack)();
#endif /* CALLBACKS_H_ */
Run Code Online (Sandbox Code Playgroud)
在单个C文件中,它们被初始化为
的callbacks.c
#include "callbacks.h"
void (*putPixelCallBack)();
void (*putImageCallBack)();
Run Code Online (Sandbox Code Playgroud)
其他C文件访问此回调函数:
paint_node.c
#include "callbacks.h"
void paint_node(node *node,int index){
//Call callbackfunction
.
.
putPixelCallBack(node->x,node->y,index);
}
Run Code Online (Sandbox Code Playgroud)
我编译这些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();
}
Run Code Online (Sandbox Code Playgroud)
但是在编译它时会出现错误:
sacmtest.cpp:在成员函数'void Sacm :: doDetection()'中:sacmtest.cpp:113:错误:ISO C++禁止获取非限定或带括号的非静态成员函数的地址,以形成指向成员函数的指针.说'&Sacm :: paintPixel'sacmtest.cpp:113:错误:从'void(Sacm :: )(int,int,int)'转换为'void()()'
有小费吗?
这在C++ FAQ [ 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
}
Run Code Online (Sandbox Code Playgroud)
你必须以某种方式正确设置全局变量.