Function pointer to class method as argument - c++

As you can see by my code, I'm trying to create a onClick event for a button that invoke a function from another class (I'm trying to make my custom button class instead of using win32 default ones for testing).
But even if this does not throw any error, it just doesn't invoke the given method.
This is the function signature inside Button.hpp
void onClick(POINT pt, void (ButtonsHandler::*clicked)(void));
This is the implementation inside Button.cpp (Using clicked() throws C++ expression preceding parentheses of apparent call must have pointer-to function type)
void Button::onClick(POINT pt, void (ButtonsHandler::*clicked)(void))
{
if (PtInRect(&textRect, pt) != 0)
{
clicked;
}
}
And this is where I actually call it
mainMenu.getPlay().onClick(pt, &ButtonsHandler::onPlay);
EDIT: solved thank you guys
I was just not creating a ButtonsHandler object to execute the non-static function
Here's the correct code I was missing.
void Button::onClick(POINT pt, void (ButtonsHandler::*clicked)(void)) {
if (PtInRect(&textRect, pt) != 0) {
ButtonsHandler bh;
(bh.*clicked)();
}
}

It just doesn't invoke the given method!
The passed pointer to member function has to be called to get in effect.
I assume that the Button is inherited from the ButtonsHandler. Then, for instance, you can call with the pointer to member function with this pointer as follows:
void Button::onClick(POINT pt, void (ButtonsHandler::*clicked)(void))
{
if (PtInRect(&textRect, pt) != 0) {
(this->*clicked)();
//^^^^^^^^^^^^^^^^^^
// or
// std::invoke(clicked, this) // need to include <functional> header(Since C++17)
}
}
If both classes are unrelated, you required an instance of ButtonsHandler to call the member function. For example:
ButtonsHandler obj;
(obj.*clicked)();
// or
// std::invoke(clicked, obj) // need to include <functional> header

Related

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++ Setting member object which has const member

I am using OIS for handling my input with Ogre and currently, on KeyPress/Release a Message object like the following will be constructed and distributed among subscribers.
class Message
{
public:
Message();
~Message();
inline void SetKeyEvent(const OIS::KeyEvent& keyEvent) { _keyEvent = keyEvent; }
const OIS::KeyEvent& GetKeyEvent() const { return _keyEvent; }
private:
OIS::KeyEvent _keyEvent;
};
Since this object will be constructed/destroyed whenever input is received via keyboard, I am trying to store a pre-constructed Message object and then simply update the _keyEvent field with the new data, before distributing.
The problem is that the OIS::KeyEvent object has a const member which is preventing me from using the assignment operator. The SetKeyEvent method gives me the following syntax error:
function "OIS::KeyEvent::operator=(const OIS::KeyEvent &)" (declared implicitly) cannot be referenced -- it is a deleted function
I was wondering what the best way to achieve this functionality would be?
Thanks in advance
EDIT: Just to clarify, I already use initializer lists when possible. My intention is to have the Message object pre-constructed and then update the _keyEvent field with the new event data from the KeyPress event which OIS fires, using the SetKeyEvent method. I would like to know if this is possible and if so, what the best way to do it would be.
The copy operator is deleted, so you must work with pointers.
class Message
{
public:
Message();
~Message();
inline void SetKeyEvent(OIS::KeyEvent* keyEvent) { _keyEvent = keyEvent; }
const OIS::KeyEvent& GetKeyEvent() const { return _keyEvent; }
private:
OIS::KeyEvent* _keyEvent;
};
And now it's better to check if the argument in the setter isn't nullptr.
inline void SetKeyEvent(OIS::KeyEvent* keyEvent)
{
assert(keyEvent != nullptr);
_keyEvent = keyEvent;
}
assert() needs #include <assert.h>
EDIT:
Sorry, forgot the getter method. You must use pointers, too.
const OIS::KeyEvent* keyEvent = &Message.GetKeyEvent();
Where Message is your class instance.
It is possible by using placement new and an explicit destructor call, things you normally should never do:
inline void SetKeyEvent(const OIS::KeyEvent& keyEvent)
{
_keyEvent.~KeyEvent();
new (&_keyEvent) OIS::KeyEvent(keyEvent);
}
This is bad ugly horrible code, use at your own risk.

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

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.

Pass any member function of any class as a Callback function

I'm working on a OpenGL menu which contains some buttons. I want to be able to associate an action (member function (with a fixed signature) of any class!) to a button which gets executed when the button is pressed. I can do it right now but only for one type. I want to be able to use any member function of any class for my callback.
Right now I'm doing it like this:
#define BUTTONCALLBACK(Func) bind1st( mem_fun( &ClassICanSupport::Func ), this )
I can then create a button like this:
Button* b = new Button("Bla", BUTTONCALLBACK(functionIWanttoCall));
The Callback function has the following signature:
void callback(Button* source);
When I press the button I can execute the callback function which I passed.
I had a look at boost::bind but I couldn't really find a way to tackle the problem. Furthermore all my classes are derived from a class Object so I thought about a void* which I could convert to the right class with some typeid hack but I was unable to get it working. At the end I always had the problem that I couldn't completly eliminate the class type of the callback function (which would be necessary to save the function pointer in my button class) and still being able to call the function.
Do you have any idea how to tackle this problem?
Don't use pointers, use boost::function together with boost::bind (or std::function and std::bind if C++0x), something like
// in Button class (or whatever signature you need)
Button(const std::string&, boost::function<void(Button*)> callback) // ...
// you can then use callback as a function
// in calling code
Button *b = new Button("..", boost::bind(&Class::func, this));
You should use a function<void(Button*)> object. These are run-time polymorphic and can be used with any object that supports void operator()(Button*). You can find one in Boost, TR1 and C++0x. boost::bind works well with these objects.
Well, the easiest way would be with virtual functions, if you don't want to pull in Boost or don't have access to C++0x.
#include <iostream>
// fwd declare
class Button;
class BtnCallbackBase{
public:
virtual void operator()(Button*) = 0;
};
template<class C>
class BtnCallback : public BtnCallbackBase{
private:
typedef void (C::*callback_func)(Button*);
C* _object;
callback_func _onclick;
public:
BtnCallback(C* obj, callback_func func)
: _object(obj)
, _onclick(func)
{}
virtual void operator()(Button* btn){
(_object->*_onclick)(btn);
}
};
class Button{
public:
Button()
: _onclick(0)
{}
void Click(){
if(_onclick != 0)
(*_onclick)(this);
}
template<class C>
void RegisterCallback(C* obj, void (C::*func)(Button*)){
// cleanup old callback, deleting null pointer is a noop
delete _onclick;
_onclick = new BtnCallback<C>(obj,func);
}
~Button(){
delete _onclick;
}
private:
BtnCallbackBase* _onclick;
};
class MyClass{
public:
void ExampleCallback(Button* btn){
std::cout << "Callback works!\n";
}
};
int main(){
Button btn;
MyClass test;
btn.RegisterCallback(&test, &MyClass::ExampleCallback);
btn.Click();
}
Full example on Ideone.
If you want a solution to your problem without using Boost library / without using new C++ features then one of the best choice is Generic Callbacks Dispatcher discussed by Danny Kalev / Herb Sutter.
http://www.gotw.ca/gotw/083.htm

How to pass a Function pointer without exposing class details

I'm creating a library that needs to allow the user to set a callback function.
The interface of this library is as below:
// Viewer Class Interface Exposed to user
/////////////////////////////
#include "dataType_1.h"
#include "dataType_2.h"
class Viewer
{
void SetCallbackFuntion( dataType_1* (Func) (dataType_2* ) );
private:
dataType_1* (*CallbackFunction) (dataType_2* );
}
In a typical usage, the user needs to access an object of dataType_3 within the callback.
However, this object is only known only to his program, like below.
// User usage
#include "Viewer.h"
#include "dataType_3.h"
// Global Declaration needed
dataType_3* objectDataType3;
dataType_1* aFunction( dataType_2* a)
{
// An operation on object of type dataType_3
objectDataType3->DoSomething();
}
main()
{
Viewer* myViewer;
myViewer->SetCallbackFunction( &aFunction );
}
My Question is as follows:
How do I avoid using an ugly global variable for objectDataType3 ?
(objectDataType3 is part of libraryFoo and all the other objects dataType_1, dataType_2 & Viewer are part of libraryFooBar) Hence I would like them to remain as separate as possible.
Don't use C in C++.
Use an interface to represent the fact you want a notification.
If you want objects of type dataType_3 to be notified of an event that happens in the viewer then just make this type implement the interface then you can register the object directly with the viewer for notification.
// The interface
// Very close to your function pointer definition.
class Listener
{
public: virtual dataType_1* notify(dataType_2* param) = 0;
};
// Updated viewer to use the interface defineition rather than a pointer.
// Note: In the old days of C when you registered a callback you normally
// also registered some data that was passed to the callback
// (see pthread_create for example)
class Viewer
{
// Set (or Add) a listener.
void SetNotifier(Listener* l) { listener = l; }
// Now you can just inform all objects that are listening
// directly via the interface. (remember to check for NULL listener)
void NotifyList(dataType_2* data) { if (listener) { listener->notify(data); }
private:
Listener* listener;
};
int main()
{
dataType_3 objectDataType3; // must implement the Listener interface
Viewer viewer;
viewer.SetNotifier(&objectDataType3);
}
Use Boost.Function:
class Viewer
{
void SetCallbackFuntion(boost::function<datatype_1* (dataType_2*)> func);
private:
boost::function<datatype_1* (dataType_2*)> CallbackFunction;
}
Then use Boost.Bind to pass the member function pointer together with your object as the function.
If you don't want or can't use boost, the typical pattern around callback functions like this is that you can pass a "user data" value (mostly declared as void*) when registering the callback. This value is then passed to the callback function.
The usage then looks like this:
dataType_1* aFunction( dataType_2* a, void* user_ptr )
{
// Cast user_ptr to datatype_3
// We know it works because we passed it during set callback
datatype_3* objectDataType3 = reinterpret_cast<datatype_3*>(user_ptr);
// An operation on object of type dataType_3
objectDataType3->DoSomething();
}
main()
{
Viewer* myViewer;
dataType_3 objectDataType3; // No longer needs to be global
myViewer->SetCallbackFunction( &aFunction, &objectDataType3 );
}
The implementation on the other side only requires to save the void* along with the function pointer:
class Viewer
{
void SetCallbackFuntion( dataType_1* (Func) (dataType_2*, void*), void* user_ptr );
private:
dataType_1* (*CallbackFunction) (dataType_2*, void*);
void* user_ptr;
}
boost::/std:: function is the solution here. You can bind member functions to them, and in addition functors and lambdas, if you have a lambda compiler.
struct local {
datatype3* object;
local(datatype3* ptr)
: object(ptr) {}
void operator()() {
object->func();
}
};
boost::function<void()> func;
func = local(object);
func(); // calls object->func() by magic.
Something like this is simple to do:
class Callback
{
public:
virtual operator()()=0;
};
template<class T>
class ClassCallback
{
T* _classPtr;
typedef void(T::*fncb)();
fncb _cbProc;
public:
ClassCallback(T* classPtr,fncb cbProc):_classPtr(classPtr),_cbProc(cbProc){}
virtual operator()(){
_classPtr->*_cbProc();
}
};
Your Viewer class would take a callback, and call it using the easy syntax:
class Viewer
{
void SetCallbackFuntion( Callback* );
void OnCallCallback(){
m_cb->operator()();
}
}
Some other class would register the callback with the viewer by using the ClassCallback template specialization:
// User usage
#include "Viewer.h"
#include "dataType_3.h"
main()
{
Viewer* myViewer;
dataType_3 objectDataType3;
myViewer->SetCallbackFunction( new ClassCallback<dataType_3>(&objectDataType3,&dataType_3::DoSomething));
}
You're asking several questions mixed up in here and this is going to cause you lots of confusion in your answers.
I'm going to focus on your issue with dataType_3.
You state:
I would like to avoid declaring or
including dataType_3 in my library as
it has huge dependencies.
What you need to do is make an interface class for dataType_3 that gives the operations -- the footprint -- of dataType_3 without defining everything in it. You'll find tips on how to do that in this article (among other places). This will allow you to comfortably include a header that gives the footprint for dataType_3 without bringing in all of its dependencies. (If you've got dependencies in the public API you may have to reuse that trick for all of those as well. This can get tedious, but this is the price of having a poorly-designed API.)
Once you've got that, instead of passing in a function for callback consider having your "callback" instead be a class implementing a known interface. There are several advantages to doing this which you can find in the literature, but for your specific example there's a further advantage. You can inherit that interface complete with an instantiated dataType_3 object in the base class. This means that you only have to #include the dataType_3 interface specification and then use the dataType_3 instance provided for you by the "callback" framework.
If you have the option of forcing some form of constraints on Viewer, I would simply template that, i.e.
template <typename CallBackType>
class Viewer
{
public:
void SetCallbackFunctor(CallBackType& callback) { _callee = callback; }
void OnCallback()
{
if (_callee) (*_callee)(...);
}
private:
// I like references, but you can use pointers
boost::optional<CallBackType&> _callee;
};
Then in your dataType_3 implement the operator() to do as needed, to use.
int main(void)
{
dataType_3 objectDataType3;
// IMHO, I would construct with the objectDataType3, rather than separate method
// if you did that, you can hold a direct reference rather than pointer or boost::optional!
Viewer<dataType_3> viewer;
viewer.SetCallbackFunctor(objectDataType3);
}
No need for other interfaces, void* etc.