Avoiding a static member function in c++ when using a callback interface from C

守給你的承諾、 提交于 2019-12-10 17:28:33

问题


I would like to access the data within this member function that is static. Right now the member function is static so that I can use it with a third party API written in C that has typdef function pointer for callback purposes. Based on the info below, what is the best way to get around the need to create a static function in order to use the data from the following function member within other member functions of my class that are non-static. Maybe there is a way to still use this static function but still overcome the inability to mix static with non-static variables. My code does works as is but with no ability to access the data in the following callback function.

void TextDetect::vtrCB(vtrTextTrack *track, void *calldata) /*acts as a callback*/
{
/*specifically would like to take data from "track" to a deep copy so that I don't loose   scope over the data withing that struct */

}

In an associated API written in C, there are the following two lines of code that I am forced to use:

 typedef void (*vtrCallback)(vtrTextTrack *track, void *calldata);
 int vtrInitialize(const char *inifile, vtrCallback cb, void *calldata);

Here is the header of my class:

 #include <vtrapi.h>
 #include <opencv.hpp>

 class TextDetect {
const char * inifile;
vtrImage *vtrimage;
int framecount;
 public:
TextDetect();
~TextDetect();
static void vtrCB(vtrTextTrack *track, void *calldata);
int vtrTest(cv::Mat);
bool DrawBox(cv::Mat&);

  };


  TextDetect::TextDetect() : inifile("vtr.ini")
  {
if (vtrInitialize(inifile, vtrCB /*run into problems here*/, NULL) == -1)
    std::cout << "Error: Failure to initialize" << std::endl;
vtrimage = new vtrImage;
framecount = 0;

  }

  void TextDetect::vtrCB(vtrTextTrack *track, void *calldata) /*acts as a callback*/
 {
/*specifically would like to take data from "track" to a deep copy so that I don't loose   scope over the data withing that struct */

 }

回答1:


I am not sure I understand your precise situation, but here is the standard idiom for wrapping a C++ method into a C callback API:

/*regular method*/
void TextDetect::vtrCB(vtrTextTrack *track)
{
   // do all the real work here
}

/*static method*/
void TextDetect::vtrCB_thunk(vtrTextTrack *track, void *data)
{
   static_cast<TextDetect *>(data)->vtrCB(track);
}

and then, assuming the function that should call vtrInitialize is also a TextDetect method, you write the call like this:

   vtrInitialize(inifile, TextDetect::vtrCB_thunk, static_cast<void *>(this));


来源:https://stackoverflow.com/questions/11513071/avoiding-a-static-member-function-in-c-when-using-a-callback-interface-from-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!