non-member function pointer as a callback in API to member function - c++

I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class in C++ but I'm getting compilation errors.
The API definition is:
typedef void (__stdcall *STREAM_CALLBACK)(void *userdata);
__declspec(dllimport) int __stdcall set_stream_callback(
STREAM_CALLBACK streamCB, void *userdata);
One example file, provided by the third party, is:
void __stdcall streamCB(void *userdata)
{
// callback implementation
}
int main(int argc, const char argv[])
{
int mid = 0;
set_stream_callback(streamCB, &mid);
}
And that works fine.
However when I try to use that in a class, I have an error:
error C3867: 'MyClass::streamCB': function call missing argument list;
use '&MyClass::streamCB' to create a pointer to member
The suggestion to use
&MyClass::streamCB
doesn't work.
I understood that the set_stream_callback only accepts a non-member function.
The problem is very similar to
How can I pass a class member function as a callback?
in which Johannes makes a concise suggestion, however I do not understand it very well. Could anyone expand a bit, if I am correct that it is relevant to this question?
I have tried:
void __stdcall MyClass::streamCB(void *userdata)
{
// callback implementation
}
static void MyClass::Callback( void * other_arg, void * this_pointer ) {
MyClass * self = static_cast<ri::IsiDevice*>(this_pointer);
self->streamCB( other_arg );
}
//and in the constructor
int mid = 0;
set_stream_callback(&MyClass::Callback, &mid);
But
error C2664: 'set_stream_callback' : cannot convert parameter 1 from
'void (__cdecl *)(void *,void *)' to 'STREAM_CALLBACK'
How do I get around this?
Edit1: Also, I want to use userdata inside the streamCB callback.

The idea of calling a member function from a callback taking only non-member functions is to create a wrapper for you member function. The wrapper obtains an object from somewhere and then calls the member function. If the callback is reasonably well designed it will allow you to pass in some "user data" which you'd use to identify your object. You, unfortunately, left out any details about your class so I'm assuming it looks something like this:
class MyClass {
public:
void streamCB() {
// whatever
}
// other members, constructors, private data, etc.
};
With this, you can set up your callback like so:
void streamCBWrapper(void* userData) {
static_cast<MyClass*>(userData)->streamCB()
}
int main() {
MyClass object;
set_stream_callback(&streamCBWrapper, &object);
// ...
}
There are various games you can play with how to create the streamCBWrapper function (e.g., you can make it a static member of your class) but all come down to the same: you need to restore your object from the user data and call the member function on this object.

You can achieve what you want to do by turning the userdata into a property of MyClass. Then you don't have to pass it to MyClass::Callback, which would be impossible, since you can only pass one parameter, and it would be the object instance.
Here's an example.
void __stdcall MyClass::streamCB()
{
// callback implementation
}
static void MyClass::Callback(void * this_pointer ) {
MyClass * self = static_cast<MyClass>(this_pointer);
self->streamCB();
}
MyClass::MyClass(void *userdata) {
// do whatever you need to do with userdata
// (...)
// and setup the callback at C level
set_stream_callback(&MyClass::Callback, (void *)this);
}
In your example, the int mid variable would become a property of that class, and thus be accessible from the callback implementation streamCB.

Related

How to bind a memberfunction to a library callback?

I am searching for a solutiuon to assign a memberfuction Callback to the extLibrary->OnNewFrame where OnNewFrame is a pointer-to-function type.
class Test
{
public:
void init();
void Callback(ImageDataType, int);
private:
};
void Test::init(){
extLibrary=new CameraLib;
extLibrary->OnNewFrame = Test::Callback;
//OnNewFrame is a pointer-to-function type
}
void Test::Callback(ImageDataType data, int n){
doImageProc();
}
If I change the Code above to static void Callback(ImageDataType, int), the code runs fine, but of course I can not access the variables of the Test Class in Callback .
I think I have to init the Class and pass the memberfunction to the lib's pointer-to-function type after, but I don't know how to do that properly.
EDIT
Sorry, this is my first post and I provided wrong and incomplete information. I will try to improve this post as far as I am able to.
To clarify what the library actually needs:
typedef void (__stdcall *GrabNewFrame) (HANDLE h, int i);
//this is the pointer to function definition
...
//after that in the lib-class:
class CameraLib
{
...
public:
GrabNewFrame OnNewFrame;
...
}
OnNewFrame gets called by the lib every time a frame arrives from the camera.
So as far as I know, I have to assign my own void function to OnNewFrame . Without OOP this works like a charm. But with classes I do not get a memberfunction assigned to OnNewFrame ...

Function Pointer Arduino as Callback Bluefruit Library

I have been trying to pass a callback to the setConnectCallback() function in the Bluefruit Library. When I pass the function names connect_callback into setConnectCallback()
I am getting the error invalid use of non-static member function of type 'void (AumeBluetooth::)()'
The function setConnectCallback() looks like it is asking for a function pointer:
exerpt from Adafruit_BLE Arduino Library:
/******************************************************************************/
/*!
#brief Set handle for connect callback
#param[in] fp function pointer, NULL will discard callback
*/
/******************************************************************************/
void Adafruit_BLE::setConnectCallback( void (*fp) (void) )
{
this->_connect_callback = fp;
install_callback(fp != NULL, EVENT_SYSTEM_CONNECT, -1);
}
I have a class "AumeBluetooth" defined as such, which I attempted to implement a function pointer to call connect_callback:
.h
class AumeBluetooth {
public:
bool isConnected = false;
Adafruit_BluefruitLE_SPI *_ble;
void error(const __FlashStringHelper*err);
void begin();
AumeBluetooth();
void loop();
void connect_callback(void);
};
.cpp
#include "AumeBluetooth.h"
#include <SPI.h>
#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"
#include "BluefruitConfig.h"
AumeBluetooth::AumeBluetooth() {
}
void AumeBluetooth::begin() {
isConnected = false;
Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);
_ble = &ble;
if ( !_ble->begin() )
{
error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?"));
}
_ble->echo(false);
_ble->info();
_ble->setMode(BLUEFRUIT_MODE_DATA);
void (AumeBluetooth::*cc)(void) = &AumeBluetooth::connect_callback;
ble.setConnectCallback(this->*cc);
}
void AumeBluetooth::connect_callback(void) {
Serial.print("BLUETOOTH IS CONNECTED");
isConnected = true;
}
}
Not sure what to do try next. Thanks!
setConnectCallback is looking for a static function pointer. As the error message says, you are passing it a non-static function pointer.
Your callback function must be a static function - either a free function, or a class function that is specifically designated 'static' and therefore has no access to class variables.
This is a tricky API, because it also looks like the function parameter list is (void), which means you don't have a way to pass in an index or a pointer to tie it to a class instance. You only get one callback to a static function, and it is up to your code to know which class instance the callback might be for.
So, your connect_callback function won't be able to set a class variable isConnected inside the callback. You will only be able to access global/static variables.
I would expect the begin() and loop() function calls also to be static, non-class functions. It looks like maybe you are trying to put a class wrapper around code that doesn't have to be a class.

C++ register callback from server

I've prototype of callback as:
typedef void (*update)(int id,...);
typedef void (*destroy)(int id,...);
typedef void (*create)(int id, update* _update, destroy* _destroy);
And than create callbacks function:
void updateCB(int id,...){/*Add id to collection*/}
void destroyCB(int id,...){/*Remove id from collection*/}
void createCB(int id,update* _update, destroy* _destroy)
{
//Register Callbacks
*_update = updateCB;
*_destroy = destroyCB;
}
When I register callbacks compiler give me error:
error: cannot convert 'ClassName::updateCB' from type 'void
(ClassName::)(int,...)' to type 'update {aka void (*)(int..)}'
How can I valid register callbacks?
You are trying to use member functions which is impossible in this case. This happens because every member function ( if it is not static ) carries with itself hidden pointer to class instance called this.
You need to use global functions or static member functions.

boost member function pointers

I am very new to the boost libraries.
I was trying to accomplish something for a graphical program, by binding the callbacks passed
to glutDisplayFunc(), etc to a single class.
I wanted to accomplish this without having some constant global class object.
To explain in code:
class CallbackHolder {
public:
void dostuff(void) {
// etc.
}
};
void bind() {
glutIdleFunc((new CallbackHolder())->dostuff);
}
I know this is possible through the usage of boost::bind and boost::function.
One issue I did see however was converting the boost::function back to a normal function pointer.
How would you accomplish this?
You can't convert from boost::function to a normal function pointer, and you can't convert from a member function pointer to a normal function pointer. There are workarounds for functions accepting callback where you can provide user data.
Unfortunately the glut interface doesn't let you provide user data. This means you're stuck with the ugliest solution, using a global variable and a normal function.
class CallbackHolder {
public:
void dostuff(void) {
// etc.
}
};
CallbackHolder * g_callbackHolder = NULL;
void call_callback_holder(void) {
if(g_callbackHolder) g_callbackHolder->dostuff();
}
void bind() {
g_callbackHolder = new CallbackHolder();
glutIdleFunc( &call_callback_holder );
}

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

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 */
}
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));