Anik Islam
Anik Islam

Reputation: 1

Callback function and void pointer C++

ps3000aGetStreamingLatestValues
(
int16_t handle,
ps3000aStreamingReady lpPs3000AReady,
void * pParameter
)
  1. lpPs3000AReady, a pointer to your ps3000aStreamingReady callback function

  2. pParameter, a void pointer that will be passed to the ps3000aStreamingReady callback. The callback may optionally use this pointer to return information to the application.

And here is the ps3000aStreamingReady callback function:

typedef void (CALLBACK *ps3000aStreamingReady)
(
int16_t handle,
int32_t noOfSamples,
uint32_t startIndex,
int16_t overflow,
uint32_t triggerAt,
int16_t triggered,
int16_t autoStop,
void * pParameter
)

My question is how I can declare pParameter in my main function? pParameter use as a communicator between those two functions and it's a void pointer because it might have to pass any kinds of data.Somehow I have to allocate memory before pass this void pointer as a arguments on those function. But how can do that?

Upvotes: 0

Views: 3874

Answers (1)

Jarod42
Jarod42

Reputation: 217085

Traditional C-way for callback to allow extra parameter is to have extra void* that user provides.

using callback = bool (int, int, void* userData);

struct CallBack
{
    bool operator ()(int a, int b) { /*..*/ }

    // extra members ...
};

bool run_callback(int a, int b, void* userData) {
    CallBack* c = reinterpret_cast<CallBack*>(userData);

    return (*c)(a, b);
}

with possible usage:

CallBack t(true); // Care to lifetime, should still be there when `run_callback` is called
Register(&run_callback, &t); // Would call later run_callback(2, 3, &t);

If you don't need that extra parameter, you might pass your regular function and nullptr

bool run_callback(int a, int b, void*) {
    // ...
}

and

Register(&run_callback, nullptr); // Would call later run_callback(2, 3, nullptr);

For C++ way of type erasure, you might use std::function.

Upvotes: 1

Related Questions