指定C ++实例方法到全球函数指针? [英] Assign C++ instance method to a global-function-pointer?

查看:126
本文介绍了指定C ++实例方法到全球函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候,

我的项目结构如下:

\- base  (C static library)
     callbacks.h
     callbacks.c
     paint_node.c
     . 
     .
     * libBase.a

\-app (C++ application)
     main.cpp

在C库'基地',我已经宣布全球函数指针为:

In C library 'base' , I have declared global-function-pointer as:

在singleheader文件

in singleheader file

callbacks.h

callbacks.h

#ifndef CALLBACKS_H_
#define CALLBACKS_H_

extern void (*putPixelCallBack)();
extern void (*putImageCallBack)();

#endif /* CALLBACKS_H_ */

在单个C文件中它们被初始化为

in single C file they are initialized as

的callbacks.c

callbacks.c

#include "callbacks.h"
void (*putPixelCallBack)();
void (*putImageCallBack)();

其他的C文件访问此回调函数为:

Other C files access this callback-functions as:

paint_node.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

I compile these C files and generate a static library 'libBase.a'

然后在C ++应用程序,

Then in C++ application,

我想C ++实例方法分配到此全局函数指针:

I want to assign C++ instance method to this global function-pointer:

我不喜欢的东西如下:

在Sacm.cpp文件

in Sacm.cpp file

#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();
}

但是,当编译它给人的错误:

But when compiling it gives the error:

sacmtest.cpp:在成员函数'无效
  SACM :: doDetection():
  sacmtest.cpp:113:错误:ISO C ++
  禁止服用的地址
  不合格或括号
  非静态成员函数,以形成一个
  成员函数指针。说
  '和; SACM :: paintPixel'sacmtest.cpp:113:
  错误:从'转换无效
  (SACM :: )(INT,INT,INT)'到'无效
  (
的)()

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 ++的常见问题,的 33.2 。这不起作用,因为指针不与特定对象实例相关联。该解决方案给出那里,创建一个使用特殊对象的全局函数:

This is the C++ FAQ, 33.2. This doesn't work, because the pointer isn't associated with a particular object instance. The solution is given there too, create a global function that uses a particular object:

 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
}

您必须以某种方式设置全局变量正常。

You have to somehow setup the global variable properly.

这篇关于指定C ++实例方法到全球函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆