Я работаю с поставщиком данных, который предлагает API в стиле C. Он ожидает, что моя функция обработчика данных будет предоставлена как указатель на функцию. Я пытаюсь инкапсулировать свою часть логики в классе, где обработчик является функцией-членом. Я не уверен, как это сделать. Фрагмент кода ниже показывает мою дилемму.
extern "C"
{
/**
* This is part of my data provider's C API (which I cannot change)
* It asks me to put my data handler in a function, then register
* it as a C-style function pointer.
*/
void set_update_callback(void (*p)(struct Data *));
}
/** I tried to encapsulate this data service within a class */
class MyDataClass
{
private:
/** Data should pushed to this queue.
* The queue is created outside my class, then its pointer is passed in from the constructor (below)
*/
queue* _data_out_queue;
public:
MyDataClass(queue* data_out_queue): _data_out_queue(data_out_queue) {}
/** Subscribe to the data provider using my handler function */
void subscribe()
{
set_update_callback(handle_data);
}
/**
* This handler function is where the dilemma is:
* - It needs to be static because it needs to be converted to a plain C-style function pointer
* - It needs to be non-static because it needs to write to the member object _data_out_queue
*/
static void handle_data(struct Data *d)
{
// parse data from *d and push into _data_out_queue
}
}
Я пытаюсь найти чистое решение на C++, не вынося ничего в глобальное пространство. Любые рекомендации приветствуются!
Я работаю с поставщиком данных, который предлагает API в стиле C. Он ожидает, что моя функция обработчика данных будет предоставлена как указатель на функцию. Я пытаюсь инкапсулировать свою часть логики в классе, где обработчик является функцией-членом. Я не уверен, как это сделать. Фрагмент кода ниже показывает мою дилемму. [code]extern "C" { /** * This is part of my data provider's C API (which I cannot change) * It asks me to put my data handler in a function, then register * it as a C-style function pointer. */ void set_update_callback(void (*p)(struct Data *)); }
/** I tried to encapsulate this data service within a class */ class MyDataClass { private:
/** Data should pushed to this queue. * The queue is created outside my class, then its pointer is passed in from the constructor (below) */ queue* _data_out_queue;
/** Subscribe to the data provider using my handler function */ void subscribe() { set_update_callback(handle_data); }
/** * This handler function is where the dilemma is: * - It needs to be static because it needs to be converted to a plain C-style function pointer * - It needs to be non-static because it needs to write to the member object _data_out_queue */ static void handle_data(struct Data *d) { // parse data from *d and push into _data_out_queue } } [/code] Я пытаюсь найти чистое решение на C++, не вынося ничего в глобальное пространство. Любые рекомендации приветствуются!