Dynamically create a function and get a pointer - c++

I am using Arduino and motor encoders to track the rotations of a motor. To do this, I am using interrupts on the Arduino. I can create a function, an ISR, that will be executed by the processor whenever the signal changes on a pin. That Interrupt/ISR combinations works like this:
void setup() {
attachInterrupt(1,ISR_function,FALLING);
}
void ISR_function() {
// do something
}
Seeing as I have multiple motors with encoders, I decided I would make a class to handle this. However, the attachInterrupt method requires a function pointer, and I am aware that in C++ you cannot have a pointer to a method function of an instance of an object. So something like this will not work:
class Encoder {
public:
Encoder(void);
void ISR_function(void);
private:
// Various private members
}
Encoder::Encoder() {
attachInterrupt(1,ISR_function,FALLING);
}
Encoder::ISR_function() {
// Do some interrupt things with private members
}
Because ISR_function is not static. The ISR_function however executes code that is dependent on the the private data members of each specific instance.
Is it possible to create a function dynamically? And then retrieve a pointer to that function? Almost like in javascript:
class Encoder {
public:
Encoder(void);
void* ISR_function(void);
private:
// Various private members
}
Encoder::Encoder() {
attachInterrupt(1,ISR_function(),FALLING);
}
Encoder::ISR_function() {
return dynamicFunctionPointer;
}
Is this possible? If not, how can accomplish what I am trying to do without manually creating separate static ISR_functions.

// type of an interrupt service routine pointer
using ISR = void(*)();
// a fake version of the environment we are working with
// for testing purposes
namespace fake_environment {
enum bob{FALLING};
ISR isrs[100] = {0};
void attachInterrupt(int i, void(*f)(), bob) {
isrs[i] = f;
}
void runInterrupt(int i) {
isrs[i]();
}
}
// type storing a pointer to member function
// as a compile-time constant
template<class T, void(T::*m)()>
struct pmf {};
// stores a pointer to a class instance
// and a member function. Invokes it
// when called with operator(). Type erases
// stuff down to void pointers.
struct funcoid {
using pfunc = void(*)(void*);
pfunc pf = 0;
void* pv = 0;
void operator()()const { pf(pv); }
template<class T, void(T::*m)()>
funcoid(T* t, pmf<T,m>):
pv(t)
{
// create a lambda, then decay it into a function pointer
// this stateless lambda takes a void* which it casts to a T*
// then invokes the member function m on it.
pf = +[](void* pt) {
(static_cast<T*>(pt)->*m)();
};
}
funcoid()=default;
};
// a global array of interrupts, which have a this pointer
// and a member function pointer type erased:
namespace client {
enum {interrupt_count = 20};
std::array<funcoid, interrupt_count> interrupt_table = {{}};
// with a bit of work, could replace this with a std::vector
}
// some metaprogramming utility code
// this lets me iterate over a set of size_t at compile time
// without writing extra helper functions at point of use.
namespace utility {
template<std::size_t...Is>
auto index_over( std::index_sequence<Is...> ) {
return [](auto&& f)->decltype(auto) {
return f(std::integral_constant<std::size_t, Is>{}...);
};
}
template<std::size_t N>
auto index_upto( std::integral_constant<std::size_t, N> ={} ) {
return index_over( std::make_index_sequence<N>{} );
}
}
// builds an array of interrupt service routines
// that invoke the same-index interrupt_table above.
namespace client {
// in g++, you'd write a helper function taking an `index_sequence`
// and take the code out of that lambda and build the array there:
std::array<ISR, interrupt_count> make_isrs() {
// creates an array of ISRs that invoke the corresponding element in interrupt_table.
// have to do it at compile time, because we are generating 20 different functions
// each one "knows" its index, then storing pointers to them.
// Could be done with a lot of copy-pasta or a macro
return ::utility::index_upto< interrupt_count >()(
[](auto...Is)->std::array<ISR, interrupt_count>{
return {{ []{ interrupt_table[decltype(Is)::value](); }... }};
}
);
}
// isr is a table of `void(*)()`, suitable for use
// by your interrupt API. Each function pointer "knows" its
// index, which it uses to invoke the appropraite `interrupt_table`
// above.
auto isr = make_isrs();
// with a bit of work, could replace this with a std::vector
}
// interrupt is the interrupt number
// index is the index in our private table (0 to 19 inclusive)
// t is the object we want to use
// mf is the member function we call
// kind is FALLING or RISING or the like
// index must be unique, that is your job.
template<class T, void(T::*m)()>
void add_interrupt( int interrupt, int index, T* t, pmf<T, m> mf, fake_environment::bob kind ) {
client::interrupt_table[index] = {t, mf};
fake_environment::attachInterrupt(interrupt,client::isr[index],kind);
}
class Encoder {
public:
Encoder():Encoder(1, 7) {};
Encoder(int interrupt, int index);
void ISR_function(void);
// my choice for some state:
std::string my_name;
};
Encoder::Encoder(int interrupt, int index) {
add_interrupt( interrupt, index, this, pmf<Encoder, &Encoder::ISR_function>{}, fake_environment::FALLING );
}
void Encoder::ISR_function() {
// display state:
std::cout << my_name << "\n";
}
int main() {
Encoder e0;
e0.my_name = "Hello World";
fake_environment::runInterrupt(1);
Encoder e1(0, 10);
e1.my_name = "Goodbye World";
fake_environment::runInterrupt(0);
}
Does not compile in g++ and uses C++14.
Does solve your problem. g++ problem is in make_isrs, which can be replaced by verbose copy-paste initialization. C++14 is from index_upto and index_over, which can similarly be reworked for C++11.
Live example.
However, ISRs are supposed to be minmal; I suspect you should just record the message and handle it elsewhere instead of interacting with object state.

To call a member function you need an instance to invoke it on, so it doesn't seem like a good choice to use for interrupts.
From pointers-to-members:
A member function is meaningless without an object to invoke it on.
Non-static member functions have a hidden parameter that corresponds to the this pointer. The this pointer points to the instance data for the object. The interrupt hardware/firmware in the system is not capable of providing the this pointer argument. You must use “normal” functions (non class members) or static member functions as interrupt service routines.
One possible solution is to use a static member as the interrupt service routine and have that function look somewhere to find the instance/member pair that should be called on interrupt. Thus the effect is that a member function is invoked on an interrupt, but for technical reasons you need to call an intermediate function first.

First of all, you can extract pointer to a class method and call it:
auto my_method_ptr = &MyClass::my_method;
....
(myClassInstance->*my_method_ptr)(); // calling via class ptr
(myclassInstance.*my_method_ptr)(); // calling via class ref
This basically passes myClassInstance pointer to MyClass::my_method as an implicit argument, accessible via this.
Unfortunately, AVR interrupt controller can't call class method, as the hardware operate on simple pointers only and can't call that method with implicit argument. You'll need a wrapper function for this.
MotorEncoderClass g_motor; // g_ for global
void my_isr() {
g_motor.do_something();
}
int main() {
// init g_motor with relevant data
// install my_isr handler
// enable interrupts
// ... do rest of stuff
return 0;
}
Create your class instance as a global variable.
Create ordinary function that calls that method
Initialize your motor class with relevant data
Install my_isr as IRQ handler.
Press start to begin :)

Related

Passing a locally-created lambda for use in a callback, then going out of scope

I'm using some (somewhat C-ish) library which involves a callback mechanism. The callback functions I can provide it take a void* as a parameter so you can pass arbitrary stuff to them. For the sake of this question let's assume the lambda doesn't take any parameters, but it does capture stuff.
Now, I need to have my callback function invoke a lambda - and it must get this lambda somehow via the void *, i.e. we have
void my_callback(void * arbitrary_stuff) {
/* magic... and somehow the lambda passed */
/* through `arbitrary_stuff` is invoked. */
}
// ...
template <T>
void adapted_add_callback(MagicTypeInvolvingT actual_callback) {
/* more magic */
libFooAddCallback(my_callback, something_based_on_actual_callback);
}
// ...
void baz();
void bar() {
int x;
adapted_add_callback([x]() { /* do something with x */ });
adapted_add_callback(baz);
}
and I want to know what to replace magic, more_magic and MagicTypeInvolvingT with.
Other than the typing challenge here, what I'm worried about, obviously, is how to make sure the data the lambda encapsulates is available on the stack for eventual use, as otherwise I should probably get some kind of segmentation fault.
Notes:
my_callback() should be synchronous, in the sense that it'll execute the lambda on whatever thread it is on and return when it returns. It's either the fooLibrary or the lambda itself which do asynchronicity.
the most straightforward way might be ( assuming the C function is guaranteed to invoke the callback exactly once, and that the lambda is valid at callback point )
void my_callback(void * arbitrary_stuff) {
(*std::unique_ptr{ static_cast<std::function<void()>*>(arbitrary_stuff) })();
}
void adapted_add_callback( std::function<void()> actual_callback ) {
libFooAddCallback(my_callback, new auto( std::move(actual_callback) ) );
}
if you don't want the function<> overhead you'll need to implement your own type erasure ...
You have a couple of issues here.
One is that you can't depend on passing the lambda itself as a void *, so you'll pretty much need to pass a pointer to the lambda (well, the closure created from the lambda, if you want to be precise). That means you'll need to ensure that the lambda remains valid until the callback completes.
The second is a question about how those captures happen - capture by value, or by reference? If you capture by value, everything's fine. If you capture by reference, you also need to ensure that anything you've captured remains valid until the callback completes. If you capture a global by reference, that should normally be fine--but if you capture a local by reference, then the local (even potentially) goes out of scope before the lambda is invoked, using the reference will cause undefined behavior.
I went in a way similar to Massimiliano Janes', but without the overhead of std::function. You have to ensure that the callback is called only once by the library.
using Callback = void(*)(void*);
// Probes the type of the argument and generates a suitable cast & invoke stub
// Caution: self-destructs after use!
template <class F>
Callback cbkWrap(F &) {
return [](void *data) {
std::unique_ptr<F> retrieved(static_cast<F*>(data));
(*retrieved)();
};
}
// Moves the functor into a dynamically-allocated one
template <class F>
void *cbkFunc(F &f) {
return new F{std::move(f)};
}
int main() {
int x = 42;
auto lambda = [&x] { std::cout << x << '\n'; };
libFooAddCallback(cbkWrap(lambda), cbkFunc(lambda));
}
See it live on Coliru
If you can ensure that the lambda outlives the potential calls, you can get rid of the dynamic memory allocations and simply pas a pointer to it as data:
// Probes the type of the argument and generates a suitable cast & invoke stub
template <class F>
Callback cbkWrap(F &) {
return [](void *data) {
auto retrieved = static_cast<F*>(data);
(*retrieved)();
};
}
int main() {
int x = 42;
auto lambda = [&x] { std::cout << x << '\n'; };
libFooAddCallback(cbkWrap(lambda), &lambda);
}
See it live on Coliru
There is unfortunately no way to give ownership of the lamba to the library without knowing exactly how many times it will be called.

Get call identifier or address of a function

Suppose that I have this code:
class MyClass
{
public:
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
};
MyClass myClassObject;
int main()
{
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
How can I know inside function what number of call is it?
Note that I will probably have 100 function calls placed in code. Also this should work in Visual Studio on Windows and Clang on Mac.
I had one workaround:
void SomeFunction(const char* indetifier = "address")
{
CheckAddress(indetifier); // This will check if address is stored. If it is not, create variables, if it is, if addresses matches use variables that are tied to that address.
}
I tried not to assign a new string to an "indetifier" and to let it to use default string ("address"). This of course didn't worked well as compiler will optimize "indetifier", so I was thinking that maybe a solution would be to disable optimizations for that variable, but I didn't because there should be some more elegant solution.
Also one thing came on my mind, maybe I could force inline a function and then get it's address, but this also seams like bad workaround.
I could also create new classes for every call but I would like to avoid this as there will be a lot of function calls and I don't want to think 100 different names.
If there is a way to create class object only at first call this would be awesome.
I hope that you understand what I want, sorry if something is not that clear as I am beginner coder.. :D
EDIT:
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
If the first call is to be tracked per object, then you need a member variable that keeps track of how many times SomeFuntion has been called for that object.
If the first call is to be tracked independent of objects, then you can use a static function variable that keeps track of how many times SomeFuntion has been called for that object.
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
So make a non-static counter?
class MyClass {
int count;
public:
MyClass () : count(0) { }
void SomeFunction () {
++ count;
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
Or just pass it as a parameter...
class MyClass {
public:
void SomeFunction (int count) {
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(1); // First call
myClassObject.SomeFunction(2); // Second call
myClassObject.SomeFunction(3); // Third call
}
But I'm really wondering what you're actually trying to do, and I highly suggest sitting back and rethinking this whole thing, because there are a number of red flags / confusing points here...
If you're only interested in checking whether it's the first call, you can add a bool SomeFunction_first_call; to the MyClass, to act as a flag. The constructor sets the bool to true. MyClass::SomeFunction() uses the conditional check if (SomeFunction_first_call) /* ... */ to determine whether it's the first call, as follows:
class MyClass
{
bool SomeFunction_first_call;
public:
MyClass() : SomeFunction_first_call(true) {}
void SomeFunction()
{
if (SomeFunction_first_call)
{
// This code only executes on first call.
do_something();
// Successfully handled first call, set flag to false.
SomeFunction_first_call = false;
}
// This code always executes.
do_something();
}
};
Similarly, if you're only concerned about the first HOWEVER_MANY_CALLS calls, where HOWEVER_MANY_CALLS is a number, you can use something like this:
#include <cstdint>
class MyClass
{
uint8_t SomeFunction_calls;
public:
MyClass() : SomeFunction_calls(0) {}
void SomeFunction()
{
// This segment will be executed until (SomeFunction_calls == HOWEVER_MANY_CALLS).
// After this, the segment will be skipped, and the counter will no longer increment.
if (SomeFunction_calls < HOWEVER_MANY_CALLS)
{
// This code only executes on first HOWEVER_MANY_CALLS calls.
do_something();
// Increment counter.
++SomeFunction_calls;
}
// This code always executes.
do_something();
}
};
Make sure to use the appropriately signed variable for the number of calls that need special handling (i.e. uint8_t for 0..255, uint16_t for 256..65,535, etc.). If different instances of MyClass will need to keep track of a different number of calls, then use a non-type template parameter to indicate this, and optionally, a defaulted typename to indicate what type the counter should be.
#include <cstdint>
template<uint64_t N, typename T = uint64_t>
class MyClass {
T SomeFunction_calls;
...
void SomeFunction()
{
if (SomeFunction_calls < N) {
...
}
...
}
};
In this case, a MyClass<4> will have special treatment for the first 4 calls to SomeFunction(), a MyClass<4444444444444444444> will have special treatment for the first 4,444,444,444,444,444,444 calls, and so on. The counter will default to uint64_t, as that should be large enough to hold the value; when only a smaller number of calls need special treatment, you can specify a smaller type, such as MyClass<4, uint8_t> or MyClass<444444444, uint32_t>.
In C++ you can use the static keyword in a local variable context to create the object only once at the first call:
#include <iostream>
struct MyObject {
MyObject() {
std::cout << "Creating instance " << this << "\n";
};
};
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
int main(int argc, const char *argv[]) {
std::cout << "About to call foo...\n";
foo();
std::cout << "... second call ...\n";
foo();
std::cout << "... third call ...\n";
foo();
return 0;
}
With the above code you will notice that only on object MyObject will be created, on the first call to foo.
Note that if your function is a template then for each instantiation of the template you will get another distinct static variable. For example with:
template<int N>
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
the all the calls to foo<1>() will use the same variable but calling instead foo<2>() will access another copy of the function (another instantiation of the function template), that will have its own distinct static variable created on the first call to foo<2>(). All static variables that have been initialized will be destroyed after the end of main when the program terminates.

Void Wrappers for Nonvoid Functions With An Argument

So, I have the following situation:
I'm coding for the mbed online compliler, on a low-memory microcontroller.
Real Time performance is very important, I want this to take less than a microsecond. 10 microseconds would be tolerable.
I'm using their timeout library, which provides an API for calling an ISR after a specified time, but requires that the ISR be a void/void function. (including a member function.
void TimeoutCallback(void) { do stuff that I want to do on timeout.} // ISR
Timeout to;
to.attach_us(&TimeoutCallback, 750) // Call TimeoutCallback in 750 us.
I created a vector of Timeout objects, which all get set at once, to the same function, with a different amount of time. I want to somehow pass into the TimeoutCallback which Timeout object called it.
My initial thought was to overload the Timeout class to allow it to accept int function(int) function pointers, and to accept a number in the overloaded attach function that gets passed to said function pointer. However, I'm unsure whether this is actually practical given the messy (and device-specific) inheritance of the Timeout class.
Now, I wonder whether there is a way to programatically create a void/void function that wraps a void/int function, and included a changeable reference int which is passed to the wrapped function.
While Tony D's solution is appropriate if using the mbed Ticker class, there is an alternative method using the mbed RtosTimer.
The RtosTimer constructor takes a void* argument that is passed to the handler on timeout. The handler has the signature:
void handler(void const* n)
Where n is the pointer argument passed to the constructor and can be used to ID the specific timeout.
Unlike Ticker where the timeout function runs in the interrupt context, for RtosTimer the handler runs as a thread, so gives greater flexibility, but potentially greater latency.
As your library can call member functions, you can create an adapter ala...
template <typename Func, Func func>
struct Adapter
{
Adapter(int n) : n_(n) { }
void f() { func(n_); }
int n_;
};
To use it:
Adapter<void(*)(int), My_Function_Expecting_An_Int> adapter(the_int);
to.attach_us(&adapter, &decltype(adapter)::f, timeout_us);
Make sure the adapter's lifetime lasts until the callback....
To call a member function:
#include <iostream>
#include <string>
#include <vector>
struct MyObj
{
void f(int n) { std::cout <<"hi " << n << "\n"; }
};
template <typename Class, typename PFunc>
struct Adapter
{
Adapter(Class& object, PFunc pFunc, int n) : object_(object), pFunc_(pFunc), n_(n) { }
void f() { (object_.*pFunc_)(n_); }
Class& object_;
PFunc pFunc_;
int n_;
};
int main()
{
MyObj myObj;
Adapter<MyObj, void(MyObj::*)(int)> adapter(myObj, &MyObj::f, 43);
adapter.f();
}

Executing bound std::function throws std::bad_function_call

I want to bind a member function to a std::function<void(void)>. I heard that member functions take one extra parameter which is the instance pointer. Therefore I call std::bind(&Class::Function, this, parameter) but when I execute the function object, it throws a runtime error.
Unhandled exception at at 0x748D4B32 in Application.exe: Microsoft C++
exception: std::bad_function_call at memory location 0x0114F4E8.
The parameter is a pointer to one of my own structs. How am I doing wrong? What additional information do you need?
Update: Here is my code.
class ModuleRenderer
{
struct Pass{ std::function<void()> Function; /* many more members... */ };
std::vector<std::pair<std::string, Pass>> passes;
enum Drawfunc{ FORMS, SKY, LIGHTS, QUAD, SCREEN };
void AddPass(std::string Name, Drawfunc Function)
{
Pass pass;
// set some of the members
// ...
passes.push_back(std::make_pair(Name, pass));
Pass *pointer = &(passes.back().second);
switch (Function)
{
case FORMS:
pointer->Function = std::bind(&ModuleRenderer::DrawForms, this, pointer);
break;
// analogeously for the other cases
// ...
}
}
void DrawForms(Pass *pass)
{
// ...
}
// is called consecutively after adding all passes
void Update()
{
for(auto i : passes)
// some initializing based on members of pass
i.Function();
}
};
A couple of different issues have been pointed out in the comments above. To resolve these, try making the following changes to your code:
struct Pass{ std::function<void(Pass *)> Function; /* ... */ };
// ...
case FORMS:
pointer->Function =
std::bind(&ModuleRenderer::DrawForms, this, std::placeholders::_1);
break;
Do not bind the Pass * to the function call just yet, because, as #molbdnilo points out, that pointer will become invalid when you call AddPass() multiple times and the vector is resized.
Since the std::function now takes a Pass *, you need to supply the correct pointer when you invoke it.
void Update()
{
for(auto& i : passes) { // <-- take a reference, don't copy
// some initializing based on members of pass
i.Function( &i ); // pass Pass * to the function
}
passes.push_back(std::make_pair(Name, pass));
Pass *pointer = &(passes.back().second);
That pointer will become invalid when you later push_back and the vector grows.
You could avoid pointers altogether and pass the index of the corresponding object instead of a pointer.
pointer->Function = std::bind(&ModuleRenderer::DrawForms, this, passes.size() - 1);
// ...
void DrawForms(size_t i)
{
Pass& pass = passes[i].second;
// Handle as before...
}

Callback to non-static method

Think of your basic GLUT programs. They simply run from a main method and contain callbacks like `glutMouseFunc(MouseButton) where MouseButton is the name of a method.
What I have done is I have encapsulated the main file into a class, so that MouseButton is no longer a static function but has an instance. But doing this gives me a compilation error :
Error 2 error C3867: 'StartHand::MouseButton': function call missing argument list; use '&StartHand::MouseButton' to create a pointer to member c:\users\angeleyes\documents\visual studio 2008\projects\capstone ver 4\starthand.cpp 388 IK Engine
It is not possible to provide a code sample as the class is quite huge.
I have tried using this->MouseButton but that gives the same error. Can't a pointer to an instance function be given for callback?
As the error message says, you must use &StartHand::MouseButton syntax to get a pointer to a member function (ptmf); this is simply mandated as part of the language.
When using a ptmf, the function you are calling, glutMouseFunc in this case, must also expect to get a ptmf as a callback, otherwise using your non-static MouseButton won't work. Instead, a common technique is for callbacks to work with a user-supplied void* context, which can be the instance pointer—but the library doing the callbacks must explicitly allow this parameter. It's also important to make sure you match the ABI expected by the external library (the handle_mouse function below).
Since glut doesn't allow user-supplied context, you have to use another mechanism: associate your objects with glut's current window. It does provide a way to get the "current window", however, and I've used this to associate a void* with the window. Then you simply need to create a trampoline to do the type conversion and call the method.
Machinery:
#include <map>
int glutGetWindow() { return 0; } // make this example compile and run ##E##
typedef std::pair<void*, void (*)(void*,int,int,int,int)> MouseCallback;
typedef std::map<int, MouseCallback> MouseCallbacks;
MouseCallbacks mouse_callbacks;
extern "C" void handle_mouse(int button, int state, int x, int y) {
MouseCallbacks::iterator i = mouse_callbacks.find(glutGetWindow());
if (i != mouse_callbacks.end()) { // should always be true, but possibly not
// if deregistering and events arrive
i->second.second(i->second.first, button, state, x, y);
}
}
void set_mousefunc(
MouseCallback::first_type obj,
MouseCallback::second_type f
) {
assert(obj); // preconditions
assert(f);
mouse_callbacks[glutGetWindow()] = MouseCallback(obj, f);
//glutMouseFunc(handle_mouse); // uncomment in non-example ##E##
handle_mouse(0, 0, 0, 0); // pretend it's triggered immediately ##E##
}
void unset_mousefunc() {
MouseCallbacks::iterator i = mouse_callbacks.find(glutGetWindow());
if (i != mouse_callbacks.end()) {
mouse_callbacks.erase(i);
//glutMouseFunc(0); // uncomment in non-example ##E##
}
}
Example:
#include <iostream>
struct Example {
void MouseButton(int button, int state, int x, int y) {
std::cout << "callback\n";
}
static void MouseButtonCallback(
void* self, int button, int state, int x, int y
) {
static_cast<Example*>(self)->MouseButton(button, state, x, y);
}
};
int main() {
Example obj;
set_mousefunc(&obj, &Example::MouseButtonCallback);
return 0;
}
Notice that you don't call glutMouseFunc directly anymore; it is managed as part of [un]set_mousefunc.
Just in case it isn't clear: I've rewritten this answer so it should work for you and so that it avoids the C/C++ linkage issue being debated. It will compile and run as-is (without glut), and it should work with glut with only minor modification: comment or uncomment the 4 lines marked ##E##.
No, a pointer to an instance function can not be given to a callback function expecting a function pointer of a certain signature. Their signatures are different. It won't compile.
Generally such APIs allow you to pass in a void* as a "context" parameter. You pass in your object there, and write a wrapper function which takes the context as the callback. The wrapper casts it back to whatever class you were using, and calls the appropriate member function.
You can't replace a static callback with an instance one. When the caller calls your callback, on what instance whoul it call? In other words, how does the caller pass in the formal 'this' argument?
The solution is to have a static callback stub and pass the instance as argument, which implies the callee must accept an arbitrary pvoid that will pass back when invoking the callback. In the stub, you can then call the non-static method:
class C {
void f() {...}
static void F(void* p) {
C* pC = (C*)p;
pC->f();
}
}
C* pC = ...;
someComponent.setCallback(&C::F, pC);
Contrary to what everyone seems to be saying, you most definitely CAN use a non-static member function as a callback method. It requires special syntax designed specifically for getting pointers to non-static members, and special syntax to call that function on a specific instance of a class. See here for a discussion of the needed syntax.
Here is sample code that illustrates how this works:
#include <cstdlib>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
class Operational
{
public:
Operational(int value) : value_(value) {};
string FormatValue() const ;
private:
int value_;
};
string Operational::FormatValue() const
{
stringstream ss;
ss << "My value is " << value_;
return ss.str();
}
typedef string(Operational::*FormatFn)() const; // note the funky syntax
Operational make_oper(int val)
{
return Operational(val);
}
int main()
{
// build the list of objects with the instance callbacks we want to call
Operational ops[] = {1, 2, 3, 5, 8, 13};
size_t numOps = sizeof(ops)/sizeof(ops[0]);
// now call the instance callbacks
for( size_t i = 0; i < numOps; ++i )
{
// get the function pointer
FormatFn fn = &Operational::FormatValue;
// get a pointer to the instance
Operational* op = &ops[i];
// call the callback on the instance
string retval = (op->*fn)();
// display the output
cout << "The object # " << hex << (void*)op << " said: '" << retval << "'" << endl;
}
return 0;
}
The output of this program when I ran it on my machine was:
The object # 0017F938 said: 'My value is 1'
The object # 0017F93C said: 'My value is 2'
The object # 0017F940 said: 'My value is 3'
The object # 0017F944 said: 'My value is 5'
The object # 0017F948 said: 'My value is 8'
The object # 0017F94C said: 'My value is 13'
You cannot use a non-static member function in this case.
Basically the type of the argument expected by glutMouseFunc is
void (*)(int, int, int, int)
while the type of your non-static member function is
void (StartHand::*)(int, int, int, int)
First problem is that types don't really match.
Second, in order to be able to call that method, the callback would have to know which object ( i.e. "this" pointer ) your method belongs to ( that's pretty much why the types are different in the first place ).
And third, I think you're using the wrong syntax to retrieve the method's pointer. The right syntax should be: &StartHand::MouseButton.
So, you have to either make that method static or use some other static method that would know which StartHand pointer to use to call MouseButton.
The following works in c++ to define a c callback function, useful for example when using glut (glutDisplayFunc, glutKeyboardFunc, glutMouseFunc ...) when you only need a single instance of this class :
MyClass * ptr_global_instance = NULL;
extern "C" void mouse_buttons_callback(int button, int state, int x, int y) {
// c function call which calls your c++ class method
ptr_global_instance->mouse_buttons_cb(button, state, x, y);
}
void MyClass::mouse_buttons_cb(int button, int state, int x, int y) {
// this is actual body of callback - ie. if (button == GLUT_LEFT_BUTTON) ...
// implemented as a c++ method
}
void MyClass::setup_glut(int argc, char** argv) { // largely boilerplate glut setup
glutInit(&argc, argv);
// ... the usual suspects go here like glutInitWindowSize(900, 800); ...
setupMouseButtonCallback(); // <-- custom linkage of c++ to cb
// ... other glut setup calls here
}
void MyClass::setupMouseButtonCallback() {
// c++ method which registers c function callback
::ptr_global_instance = this;
::glutMouseFunc(::mouse_buttons_callback);
}
In your MyClass header we add :
void mouse_buttons_cb(int button, int state, int x, int y);
void setupMouseButtonCallback();
This also works using identical logic flows to setup your glut
call to glutDisplayFunc(display)