Passing a class Member function as an Argument - c++

I have a class as follows and a main method as follows:
class Mesh
{
public:
void draw()
void draw(){}
}
int main(int argc,char* argv[])
{
Mesh mesh;
glutDisplayFunc(mesh.draw);
}
So I want to pass a member function of an object as argument, but the compiler displays the following error message:
error: argument of type ‘void (Mesh::)()’ does not match ‘void (*)()’
What am I doing wrong?

Since draw is a non-static member function, it needs an instance of the class to operate upon.
In pure C++, you would use a function object (a.k.a. "functor", see std::function or its predecessor boost::function). That's sadly not an option in C or C APIs.
In this case, since there's no data that is handed to the callback, you must make some sort of static function (either class static or file static) that does the right thing when it is called.
If you only ever have one Mesh, then it's easy: either make everything in the class static (in which case it's basically a namespace), or have a non-member function that calls draw against the one instance of your Mesh:
// at some global-ish file scope...
// we define our class
class Mesh { ... };
// and here's the one global instance of it
Mesh myOneMesh;
// and here is our global / static function that "knows"
// which instance to draw
void drawMyOneMesh() { myOneMesh.draw(); }
// then, in the main flow of your program:
glutDisplayFunc( &drawMyOneMesh );
If you have multiple meshes, it looks like the best you can do is to key it off of the current window. Without knowing much about your app or about the GLUT API, I would probably do something like this to enable a mesh-per-window callback:
#include <map>
// this could also be a class with all-static members, if one
// were so inclined. might be worth it, if only to protect 'map'
// from external meddling.
namespace WindowToMesh
{
typedef std::map< int, Mesh * > Map;
Map map;
void addMapping( int win, Mesh * mesh )
{
map.insert( { win, mesh } );
}
void removeMapping( int win )
{
map.erase( win );
}
void draw()
{
int win = glutGetWindow();
Map::iterator it = map.find( win );
if ( it != map.end() )
it.second->draw();
}
} // end namespace WindowToMesh
Now, in your main program, you can associate a new Mesh with the current window:
Mesh * m = new Mesh( ... );
WindowToMesh::addMapping( glutGetWindow(), m );
And you can associate the (effectively static) WindowToMesh::draw function as the callback:
glutDisplayFunc( &WindowToMesh::draw );
When you're ready to destroy the Mesh, make sure you're in the same window, and then:
WindowToMesh::removeMapping( glutGetWindow() );
Depending on other factors, it might make sense to do a bidirectional mapping (so you can find things by Mesh * and not just by window int, or to do a brute-force scan on the rare unregistration, etc.
I don't have an environment in which I can test that, but it should be close. Good luck!

The problem is that a member function pointer needs some information to be called, i.e. the instance to be called on, which will then be accessible by the this pointer within the implementation of the member function, so you can access member variables. I think you want to do this, since your design looks like you want to draw stuff which is defined in Mesh.
There are possibilities to turn a member function pointer into a "normal" function pointer. But you have to keep in mind that this piece of information (the instance of Mesh) has to be available once this function is called. This means that a typical transformation from a member function pointer to a "normal" function pointer adds a parameter (the instance).
But glutDisplayFunc() accepts a void(*)(void) function pointer, i.e. an empty parameter list, so it won't tell the called function anything. You have to make sure that once the passed function is called, you can howsoever reconstruct the "context", i.e. the Mesh instance.
This can be done by pointing to a Mesh instance from a global point in your code. It will always be used when you call the helper function we are about to write. So when you pass a pointer to glutDisplayFunc() our helper function knows which Mesh to use, once we told it which it should use.
class Mesh
{
public:
void draw() { ... }
}
Mesh *instance;
// Helper function called by glut:
void display() {
// Now we can access a particular instance:
instance->draw();
}
int main(int argc,char* argv[])
{
Mesh mesh;
// First point to this instance globally:
instance = &mesh;
// Then, pass our helper function which now has an empty parameter list:
glutDisplayFunc(&display);
}
This solution has a restriction. You can't reuse the same function pointer with different instances. So you can't turn any instance into a function pointer, but only one for each globally defined instance pointer. But since you just want to pass your draw function to glutDisplayFunc, you only need to do this once, so it should be fine. I just don't want to keep this "danger" from you. ;)

Related

Creating a wrapper method in C++ at runtime - prototype known

I'm currently wrapping around an API that takes function pointers and calls them back at some point. The only issue is that the prototype for this callback function provides a pointer to the state I'm wrapping around instead of my new class. My goal is to hide the original API from the user, so I need a way to dynamically create a method that calls back a different function whose prototype is instead my new class. Here's a simplified code visualisation.
struct Old_API
{
public:
typedef int (*OldCallback)(Old_API*);
void RegisterCallback(OldCallback);
};
class New_API
{
private:
Old_API* m_WrappedState;
public:
typedef int (*NewCallback)(New_API*);
New_API() { m_WrappedState = new Old_API; }
void RegisterCallback(NewCallback func)
{
// Pseudocode, obviously won't work
// This is the actual method that would be called back from Old_API
// It acts as a buffer to call the "new" format of callbacks
int CallbackLayer(Old_API* state)
{
m_WrappedState = state;
return func(this);
}
m_WrappedState->RegisterCallback(&CallbackLayer);
}
};
// This is what it would look like in runtime
int SomeCallback(New_API*)
{
// Code
}
New_API* state;
int main()
{
state = new New_API;
state->RegisterCallback(&SomeCallback);
return 0;
}
Specifications
Must be done at runtime so passing the function pointer as a template parameter won't work.
Instances of New_API are created by the user and are nearly stateless - they simply wrap around arbitrary Old_API instances.
Old_API instances are passed to the callback function and don't map to a single New_API instance. The "CallbackLayer" method is intended to remove the need for the user to have to setup the state themselves, thus hiding Old_API's implementation.
If you're fully wrapping the interface, it makes this easy.
First New_API registers its own listener on Old_API, using whatever means Old_API offers to associate the callback with that instance of New_API (could just be a field in Old_API, or if that's not available, even something like a static unordered_map<Old_API*, New_API*>).
Then, New_API has its own system for registering listeners. (You're showing function pointers here, but that's C thinking... at worst, you should have something which takes a std::function.)
When New_API gets its notification, it simply notifies its own listener(s) in turn. There's no direct mapping between listeners: Old_API will have exactly one listener, regardless of how many listeners are on New_API.

Passing function pointer with scope resolution operator arduino

I'm a newbie to arduino and programming.
I've included a library inside my own library in arduino, but first library contains a function which has a pointer function as a parameter. It is an interrupt service routine(ISR) but I need to call a function in my cpp file when interrupt is occurred. So I need to pass the pointer of that function to the first library code. It works well when I use it in .ino file, I can pass it like,
attachInterrupt(functionISR_name);
but when I use it in .cpp file, I get errors. my function is like,
void velocity::functionISR_name(){
//some code
}
but how can I pass the pointer of this function to the first library function? I tried this way but got errors,
attachInterrupt(velocity::functionISR_name);
You cannot pass a method to a function which expects a function, unless you define it static.
write it static :
static void velocity::functionISR_name()
and
attachInterrupt(&velocity::functionISR_name);
Unfortunately the static method is not bound to a specific instance any more. You should use it only together with a singleton. On Arduino you should write the class like shown below in the code snipped:
class velocity
{
static velocity *pThisSingelton;
public:
velocity()
{
pThisSingelton=this;
}
static void functionISR_name()
{
pThisSingelton->CallWhatEverMethodYouNeeded();
// Do whatever needed.
}
// … Your methods
};
velocity *velocity::pThisSingelton;
velocity YourOneAndOnlyInstanceOfThisClass;
void setup()
{
attachInterrupt(&velocity::functionISR_name);
// …other stuff…
}
This looks ugly, but in my opinion it is totally okay with Arduino as the opportunities are very limited on such a system.
Thinking again over it, I would personal go for the approach Sorin mentioned in his answer above. That would be more like that:
class velocity
{
public:
velocity()
{
}
static void functionISR_name()
{
// Do whatever needed.
}
// … Your methods
};
velocity YourOneAndOnlyInstanceOfThisClass;
void functionISR_name_delegation()
{
YourOneAndOnlyInstanceOfThisClass.functionISR_name();
}
void setup()
{
attachInterrupt(functionISR_name_delegation);
// …other stuff…
}
It would also save you some bytes for the pointer you need in the first example.
As a site note: For the future, please post the exact code (for e.g. attachInterrupt needs more parameter) and copy&paste the error messages. Usually error are exact at a place you do not suspect. This question was an exception. Normally I and other would ask for better specification.
You pass a pointer to the function but the function is a class member. Likely the call will be invalid because the this pointer will be garbage(may compile fine but will throw strange errors at runtime).
You need to define a plain vanilla function, outside of any class, and use that.
If you don't have a very complex project you can get away with having a global pointer to the class instance you should use and just delegate the call in your new function.
If you want to do thing the right way you need some mechanism to get the instance pointer I talked about above. Usually this involves either a singleton or some factory pattern.
Example:
class Foo {
void method() {
x = 5;
}
int x;
}
Having a callback on method will crash because you have an invalid pointer for this so x=5 will write 5 somewhere randomly in memory.
What you need is somehting like:
static Foo* foo_instance; // Initialized somewhere else.
void method_delegator() {
foo_instance->method();
}
Now you can pass method_delegator to the function. It will work because you now also pass foo_instance for this pointer.

Reference to non static member function must be called

I have a vector bars that contains several coloured box objects.Each box object has it's own draw and update function. Each box moves from one side of the screen to the next side. when it's outside the screen the box should be removed. I'm using iterators to move the boxes and determine when they are outside of the screen.
I'm very new to c++ and I'm having trouble getting the code to work. the function to erase an object from a vector is giving me the error Reference to non static member function must be called. I'm reading up on static and non static members but I'm still a bit lost.
here's my main header file with the relevant code
class game : public ofxiPhoneApp {
public:
void setup();
void update();
void draw();
void exit();
vector <Colorbar> bars;
bool checkBounds (Colorbar &b);
};
in my game.mm file I create the vector and iterate over it to set the properties of the coloured bar objects:
void game::setup(){
bars.assign(5, Colorbar());
for (int i = 0; i<bars.size(); i++) {
ofColor color = colors.giveColor();
bars[i].setup();
bars[i].setColor(color.r,color.g,color.b);
bars[i].setWidth(50);
bars[i].setPos(ofGetScreenHeight()-(i*50), 0);
}
}
the update function that move the bars across the screen.
void game::update(){
for(vector<Colorbar>::iterator b = bars.begin(); b != bars.end(); b++){
(*b).update();
}
//this is the part that gives the error
bars.erase((remove_if(bars.begin(), bars.end(), checkBounds),bars.end()));
}
and here's the function to check if the box is out of bounds
bool game::checkBounds (Colorbar &b){
if (b.pos.x > ofGetScreenHeight()+50) {
// do stuff with bars vector here like adding a new object
return true;
} else {
return false;
}
}
I've done some experimenting, and making the bool checkBounds (Colorbar &b);
non-static by removing it from the header file makes the code work. but the problem is that I'd also like to be able to access the bars vector in that function to add a new object when an old one is deleted. And that won't work anymore.
How can I solve this?
You need a unary functor taking a ColourBar. A member function has an implicit first parameter for this. This means it cannot be called like this:
Colorbar cb;
game::checkBounds(cb);
It needs to be bound to an instance of its class, otherwise it would not be able to access other members of that instance. So you need to bind the checkBounds member function to an instance of game. In your case, this looks like the right instance to bind:
#include <functional> // for std::bind
using std::placeholders; // for _1
...
remove_if(bars.begin(), bars.end(), std::bind(&game::checkBounds, this, _1)) ...

Circular dependency conundrums

In my C++ project, I have an Engine class, a Renderer class and an Object class.
The instance of Renderer renders instances of Object. However instances of Object add themselves or remove themselves from the list of things to render.
From a usability point of view, it should be possible to set whether an instance of Object is drawn or not from the Object, but without the circular dependency.
I have a possible solution to this problem, but I do not know if it is a good idea:
The update cycle in the game is done through an Update() function in the Engine class that calls the Update() functions for every object. When it comes to call the Update() function for each instance of Object, I could set it to check for two boolean variables in the Object class. One, for whether it should be drawn, and one for whether it is actually being drawn. This should thus allow for an instance of Object to be added or removed from the list of things to render as required.
Is it a good idea to do it this way? Is this way efficient or is there a better way without the circular dependency?
EDIT:
I have rewritten my question for greater clarity and moved the second part to a new question where it was probably more relevant and to avoid confusing things further here.
You would want Object to inherit from Rendered, and Renderer to only be aware of Rendered, not Object (See below):
#include <iostream>
#include <list>
struct Renderer;
struct Rendered
{
virtual void renderMe( Renderer& ) = 0;
protected:
//Renderer won't delete me...
virtual ~Rendered(){}
};
struct Object : Rendered
{
virtual void renderMe( Renderer& )
{
std::cout << "I'm rendered!" << std::endl;
}
};
struct Renderer
{
void add( Rendered& r )
{
renderList_.push_back( & r );
}
void remove( Rendered& r );//...use your imagination
void render()
{
for( std::list<Rendered*>::iterator i = renderList_.begin(); i != renderList_.end(); ++i )
{
(*i)->renderMe( *this );
}
}
private:
std::list<Rendered*> renderList_;
};
struct Engine
{
Renderer& renderer_;
Object myObject_;
Engine( Renderer& r )
: renderer_( r )
{
renderer_.add( myObject_ );
}
~Engine()
{
renderer_.remove( myObject_ );
}
};
int test()
{
Renderer r;
Enginer e( r );
r.render();
return 0;
}
Not sure I really understand the intention. However, i would like to revisit your original question:
Currently, in order for an instance of Object to be drawn, it needs to
add itself to the instance of Renderer's list of objects to draw. This
means it needs a pointer to the instance of Renderer, however Renderer
also needs to know about Object in order to draw it.
Why is this a problem? If you just need pointers, you can declare the class type upfront:
class Object;
class Renderer;
class Engine;
Although, even cleaner would be using an Interface class.
EDIT:
Do I understand correctly, the problem is that you want to pass Rendered instance to Object, so the object can paint itself using the renderer?
What about the Interface class then:
class Paintable
{
public:
virtual void paint(Renderer *) = 0;
};
class Object : public Paintable
{
...
}
All your paintable object will be extending from the interface. This way the Renderer class doesn't need to hold vector of Objects, but vector of pointers to Paintable. (e.g. Renderer is no longer dependent on Object)
ANSWER: to second comment
Not sure you have a choice. You need the rendering piece of code to have access to Object's internal data (color, position, etc ...) and to the Renderer handle. Your choices are have the code in Renderer accessing object's internal data. This is, I think, a bad idea, as the Renderer would need to have different code handling different objects, and also possibly accessing private members of the Object. The other way around is to have intelligent objects that can render themselves given the Renderer handle. So they can call: renderer.paintLine(...), etc. Using the Interface class is neat, as the Renderer doen't need to have any knowledge about the Objects it holds.

Build & execute a stack of void functions

I am trying to store a vector(or stack) of functions. The idea is that I have a series of functions that add & remove widgets to the main window. I use a timer alarm & whenever the alarm is called I call the function at the top of the stack of functions.
So my functions will always be of type void. My problem/misunderstanding is how to delcare a stl::stack of void functions & how do I execute that function?
class InstructionScreen
{
std::stack <void*> instructionSteps; // is this how I declare a stack of functions
void runTimerEvent()
{
if ( !instructionSteps.empty() )
{
// call the function at the top of the stack
// how do I call the function?
(*instructionSteps.top()); // is that how?
instructionSteps.pop();
}
}
void step1()
{
// here I create some widgets & add them to the main window
}
void step2()
{
// delete widgets from window
// create some different widgets & add them to the main window
}
void buildStack()
{
instructionSteps.push( (&step1()) ); // is this correct?
instructionSteps.push( (&step2()) );
}
};
A void* pointer is not a legal function pointer. It should be void (*)(), which can be made nicer with a typedef void (*stack_function)().
std::stack<stack_function> instructionSteps;
To push something into it, you don't call the function (like you do with step1()) and you certainly don't take the address of the return (which is void anyways) like you do with &step1(), you just use the function name alone:
instructionSteps.push(step1); // the & can be omitted for free functions
instructionSteps.push(&step2); // equivalent to the above, only a different function
To call stuff from the top of the stack, you actually need to do a call:
(*instructionSteps.top())();
// you missed that -- ^^
The dereference can be omitted too for reasons that would take too long to explain here, search SO. :)
instructionSteps.top()();
The syntax for a static function pointer is like so:
void (*FuncPtr)();
For a member pointer you have to use this syntax:
void (class::*FuncPtr)();
If your functions does not require the functions to be member functions it is a lot cleaner. Once you figured out what kind of functions you need it's easiest to typedef these functions like so:
typedef void(*FuncPtrType)();
typedef void(Class::*MemberFuncPtrType)();
Now you can simply declare a stack with function pointers like so:
std::stack <FuncPtrType> funcPtrStack;
std::stack <MemberFuncPtrType> memberFuncPtrStack;
To get a pointer to a function you simply use the "&" operator like you would to get an address to any other data type in C++:
FuncPtrType funcPtr = &staticFunc; // Somewhere "void staticFunc()" is defined
MemberFuncPtrType memberFuncPtr = &Class::MemberFunc; // Somewhere void "Class::MemberFunc()" is defined
To actually call the function pointers, you would use the "*" operator to get the data back from the pointer (just like any other data type in C++). The only tricky thing is for member functions they need a pointer to the class which makes it very awkward to use. That's why I recommended using static functions to begin with. In any case, here is the syntax:
(*funcPtr)(); // I just called a function with a pointer!
(this->*memberFuncPtr)(); // I just wrote some ugly code to call a member function
Having shown all that, the following code should now make sense:
std::stack <MemberFuncPtrType> memberFuncPtrStack; // Declaring the stack
memberFuncPtrStack.push( &Class::MemberFunc ); // Pushing a function
(ClassPtr->*memberFuncPtrStack.top())(); // Calling the function with ClassPtr
Declare a typedef and make a vector/stack of it:
typedef void (*funcptr)();
std::stack<funcptr> instructionSteps;
Usage:
instructionSteps.push(&step1);
instructionSteps.push(&step2);
See demo here.
Execution:
instructionSteps.top()();
Tip: Use Boost.Function, it's a lot easier. It will not only store functions with precisely the right type, but also anything else that can be called in the same way.
std::stack<boost::function<void()> instructionSteps;
int foo() { return 42; }
instructionSteps.push(foo); // Close enough - return value will be discarded.
typedef void (*fptr)();
class InstructionScreen
{
std::stack <fptr> instructionSteps;
I would typedef the function pointer to make your life easier:
typedef void(*voidFunctionPointer)(); // Assuming here that the functions take no arguments.
std::stack<voidFunctionPointer> instructionSteps; // This is very different from <void*>.
// The latter is merely a stack of void pointers.
One way of calling the top function is this:
voidFunctionPointer functionToCall = instructionSteps.top();
functionToCall();
If you want to do it without an extra declaration, I think this should work. Please correct me if I'm wrong.
instructionSteps.top()();
To build the stack, just use the function name without any trailing parentheses.
instructionSteps.push(step1);
instructionSteps.push(step2);
// ...