4

このメンバー関数内の静的なデータにアクセスしたいと思います。現在、メンバー関数は静的であるため、コールバックの目的でtypdef関数ポインターを持つCで記述されたサードパーティのAPIで使用できます。以下の情報に基づいて、静的ではないクラスの他のメンバー関数内で次の関数メンバーからのデータを使用するために静的関数を作成する必要性を回避するための最良の方法は何ですか。たぶん、この静的関数を使用する方法はありますが、静的変数と非静的変数を混在させることができないことを克服する方法があります。私のコードはそのまま動作しますが、次のコールバック関数のデータにアクセスする機能がありません。

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 */

}

Cで記述された関連APIには、次の2行のコードがあります。

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

これが私のクラスのヘッダーです:

 #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 */

 }
4

1 に答える 1

7

あなたの正確な状況を理解できるかどうかはわかりませんが、C++メソッドをCコールバック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);
}

vtrInitialize次に、呼び出す必要のある関数もメソッドであると想定してTextDetect、次のように呼び出しを記述します。

   vtrInitialize(inifile, TextDetect::vtrCB_thunk, static_cast<void *>(this));
于 2012-07-16T21:54:58.207 に答える