function pointer with known arguments - c++

I have a lot of legacy code that uses a function pointer as an argument of the form double (*f)(double). Now I have a requirement where I need to call this function from a class but function definition uses member variables. What do I do to solve this issue? For example,
void legacy_function(double (*f)(double)) { .... }
class myclass {
double a;
double b;
double c;
void mymethod(...) {
// need to call legacy_function() such that it uses a and b with one unknown
// a+b*x
}
Note that I cannot change definitions or declarations in legacy code.
I hope this is making sense. thanks for suggestions..

There's no clean way to solve this problem. It has no elegant solution within the bounds of the standard language.
One thing you can do is to provide a global or static variable that will serve as this pointer for the intermediate callback wrapper function (see below), and write a static intermediate callback wrapper function which will delecate the call to a non-static class method
class myclass {
...
static myclass *myclass_this;
double callback_wrapper(double d) {
assert(myclass_this != NULL);
return myclass_this->callback(d); // calls the actual implementation
}
};
Also write the actual callback implementation in myclass
class myclass {
...
double callback(double d) {
// do whatever you want with `a`, `b` etc.
return /* whatever */;
}
...
};
Now you can initialize myclass_this and use the intermediate callback wrapper from inside mymethod
...
void mymethod(...) {
myclass_this = this; // initilize the context
legacy_function(&callback_wrapper);
}
...
All this, of course, is terribly inelegant since it relies on global or static variables and therefore is non-reentrant.
There are alternative methods, which all happen to be non-portable and non-standard. (Read about closures and delegates).

Related

Calling C++ class methods from C using callbacks

I have a class, Component, which has to interact with C code.
//// Component.h file ////
class Component{
public:
uint8_t getdevice1Value();
void setdevice1Value(uint8_t value);
uint8_t getdevice2Value();
void setdevice2Value(uint8_t uint8_t);
private:
uint8_t device1Value;
uint8_t device2Value;
}
The object of the class would be created when its relevant thread is created in some Application.cpp file:
///////Some function where the Component is used//////
createThread(){
Component myComponent; // Scope within the thread
// Some actions
}
Now comes my C code, which happens to be event driven. Within these functions, I would like to link my Class methods:
//// device1_event.c file ////
void command_get_device_value()
{
// code
// assign variable = Component::getdevice1Value() function
// code
}
void command_set_device_value()
{
// code
// call Component::setdevice1Value(variable) passing some variable
// code
}
Similar to device1_event.c file, I have another device2_event.c where I would like to map the function calls to getdevice2Value and setdevice2Value.
I looked at the questions Using a C++ class member function (cannot be static) as a C callback function or also this Pass a C++ member function to a C function, where a struct registers the context and the function pointers.
I have a constraint in my case of not being able to dynamic allocation. So, I cannot use the new operator.
Now I have a few questions regarding these:
Is the callback concept applicable in my case?
If the first question is a yes, then:
How do I go about implementing it. I am a bit confused about this. I mean the call-functions need to be placed within the C-functions and also I need to register them once the Component instance is created. How can I exactly do this?
How do I bring the callback functions to my C files?
In this question a struct was employed. Where do I declare the 'struct'? I did try declaring it in the Component.h file and introduced it as an extern within the device1_event.c file. But I get an incomplete type error.
The classical C way of passing callbacks is to pass two values: a pointer to the callback itself, and an opaque pointer which will be passed to the callback as an additional argument (take a look at qsort_r for example). When interfacing with C++, that opaque value may be used as instance pointer; you will only need to write a thin wrapper:
class B {
void my_callback(int arg);
static void my_callback_wrapper(int arg, void *u) {
((B*)u)->my_callback(arg);
}
};
// or even:
extern "C" void my_callback_wrapper(int arg, void *u) {
((B*)u)->my_callback(arg);
}
and pass a pointer to the wrapper, along with a pointer to the object, to the C part. Be careful to use the exact same class type on both sides and not base/derived classes, for example.
Note that while it may be possible to get a pointer to the (non-static) method itself, on some compilers (tested on MSVC a long time ago) they have a special calling convention so that the pointer will not be compatible with any normal function pointer.

(New to C++) Save a function pointer that can be called later

I've spent some time trying figure out how to do this but I think I need help. If I could use templates I can avoid having to type the function, like 'B::theFuncToBeCalled', right? But that only works if it's a static method, if I'm not mistaken?
// A.h
typedef std::function <void()> CbType;
class A
{
template<typename T>
void setCallback(T &cb);
private:
template <typename T>
T callThisLater;
};
// A.cpp
template<typename T>
void A::setCallback(T &cb)
{
this->callThisLater = cb;
// later...
((CbType*)callThisLater)();
}
// B.cpp
// in constructor or wherever
{
A* a;
a->setCallback(this->theFuncToBeCalled);
// or, anonymous
CbType func = [this](){
// do something
// call theFuncToBeCalled() if I feel like it :)
};
a->setCallback(func);
}
void B::theFuncToBeCalled()
{
log("yay");
}
(If I try doing it the anonymous way I get an access violation error.)
There is much wrong here. Let's discuss that and then how to fix it:
You cannot simply define templatized functions in the implementation file: https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
c++14's variable templates are only available for static variables:
A variable template defines a family of variables or static data members
You are passing a method, and trying to use it as though you passed a function, methods implicitly take the this parameter
Once the type of callThisLater is defined to accept a method, it cannot be subsequently changed to accept a lambda with a different signature
class A is a poor re-implementation of what could be solved with a functor or even just a function pointer
Please simply eliminate class A and use a function pointer and a closure type:
auto a = &B::theFuncToBeCalled;
auto func = [=]() { (*this.*a)(); }
Rather than using a going forward simply use func
I decided to change my approach and instead of saving a pointer to a callback, I'm saving a pointer to the object the member function belongs to. It's the same amount of work, but with the benefit that if I ever need to call several different member functions, I can just do:
objRef->theFuncToBeCalled();
// later
objRef->theOtherFuncToBeCalled();
and all I need for this, is one pointer. Simple is Bestâ„¢, amiright? :) Thanks for your help!

Pass class function to another class function

sorry for possible duplicates, but I didn't understand the examples and codes snippets I found.
I have a class named "EncoderWrapper" which includes some functions. One of these functions is called "onAfterTouch" and is declared in the "EncoderWrapper.h" file.
void onAfterTouch(byte channel, byte pressure);
The functions will become a callback for another class function of a library I use
inline void setHandleAfterTouch(void (*fptr)(uint8_t channel, uint8_t pressure)) {
usb_midi_handleAfterTouch = fptr;
};
Note: I'm totally new to C++, so I want to say sorry if I'm doing some "no-gos" or mixing up some terms.
The question is: How can I pass my class function (member function?) to that "setHandleAfterTouch" function of the library?
This won't work:
void EncoderWrapper::attachMIDIEvents()
{
usbMIDI.setHandleAfterTouch(&EncoderWrapper::onAfterTouch);
}
... my IDE says
no matching function for call usb_midi_class:setHandleAfterTouch(void (EncoderWrapper::*)(byte, byte))
I've also tried
usbMIDI.setHandleAfterTouch((&this->onAfterTouch));
But this won't work ... and I don't get the approach on that.
Every Help is very appreciated ;-)
Function pointer and member function pointer have different types. You can it for yourself:
struct Test {
void fun();
};
int main() {
void(*ptr)() = &Test::fun; // error!
}
Instead, member function pointer need this syntax:
void(Test::*fun)() = &Test::fun; // works!
Why you ask? Because member function need an instance to be called with. And calling that function have a special syntax too:
Test t;
(t.*funptr)();
To accept member function pointer, you'll need to change your code to this:
inline void setHandleAfterTouch(void(EncodeWrapper::*fptr)(uint8_t, uint8_t)) {
usb_midi_handleAfterTouch = fptr;
};
Since it's rather limiting accepting only the functions from one class, I recommend using std::function:
inline void setHandleAfterTouch(std::function<void(uint8_t, uint8_t)> fptr) {
usb_midi_handleAfterTouch = std::move(fptr);
};
This will allow you to send lambda with captures, and call your member function insode it:
// we capture this to use member function inside
// v---
usbMIDI.setHandleAfterTouch([this](uint8_t, channel, uint8_t pressure) {
onAfterTouch(channel, pressure);
});
It seems you can't change, and by looking quickly at the API, it doesn't seem you have access to a state object.
In that case, if you want to use your member function, you need to introduce a global state:
// global variable
EncodeWrapper* encode = nullptr;
// in your function that sets the handle
encode = this; // v--- No capture makes it convertible to a function pointer
usbMIDI.setHandleAfterTouch([](uint8_t, channel, uint8_t pressure) {
encode->onAfterTouch(channel, pressure);
});
Another solution would be to make onAfterTouch function static. If it's static, it's pointer is not a member function pointer, but a normal function pointer.

C++: Is it possible to call an object's function before constructor completes?

In C++, is it possible to call a function of an instance before the constructor of that instance completes?
e.g. if A's constructor instantiates B and B's constructor calls one of A's functions.
Yes, that's possible. However, you are responsible that the function invoked won't try to access any sub-objects which didn't have their constructor called. Usually this is quite error-prone, which is why it should be avoided.
This is very possible
class A;
class B {
public:
B(A* pValue);
};
class A {
public:
A() {
B value(this);
}
void SomeMethod() {}
};
B::B(A* pValue) {
pValue->SomeMethod();
}
It's possible and sometimes practically necessary (although it amplifies the ability to level a city block inadvertently). For example, in C++98, instead of defining an artificial base class for common initialization, in C++98 one often see that done by an init function called from each constructor. I'm not talking about two-phase construction, which is just Evil, but about factoring out common initialization.
C++0x provides constructor forwarding which will help to alleviate the problem.
For the in-practice it is Dangerous, one has to be extra careful about what's initialized and not. And for the purely formal there is some unnecessarily vague wording in the standard which can be construed as if the object doesn't really exist until a constructor has completed successfully. However, since that interpretation would make it UB to use e.g. an init function to factor out common initialization, which is a common practice, it can just be disregarded.
why would you wanna do that? No, It can not be done as you need to have an object as one of its parameter(s). C++ member function implementation and C function are different things.
c++ code
class foo
{
int data;
void DoSomething()
{
data++;
}
};
int main()
{
foo a; //an object
a.data = 0; //set the data member to 0
a.DoSomething(); //the object is doing something with itself and is using 'data'
}
Here is a simple way how to do it C.
typedef void (*pDoSomething) ();
typedef struct __foo
{
int data;
pDoSomething ds; //<--pointer to DoSomething function
}foo;
void DoSomething(foo* this)
{
this->data++; //<-- C++ compiler won't compile this as C++ compiler uses 'this' as one of its keywords.
}
int main()
{
foo a;
a.ds = DoSomething; // you have to set the function.
a.data = 0;
a.ds(&a); //this is the same as C++ a.DoSomething code above.
}
Finally, the answer to your question is the code below.
void DoSomething(foo* this);
int main()
{
DoSomething( ?? ); //WHAT!?? We need to pass something here.
}
See, you need an object to pass to it. The answer is no.

Calling a C++ function pointer on a specific object instance

I have a function pointer defined by:
typedef void (*EventFunction)(int nEvent);
Is there a way to handle that function with a specific instance of a C++ object?
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne() { handler(1); }
};
class B
{
private:
A a;
public:
B() { a.SetEvent(EventFromA); } // What do I do here?
void EventFromA(int nEvent) { // do stuff }
};
Edit: Orion pointed out the options that Boost offers such as:
boost::function<int (int)> f;
X x;
f = std::bind1st(
std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)
Unfortunately Boost is not an option for me. Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?
You can use function pointers to index into the vtable of a given object instance. This is called a member function pointer. Your syntax would need to change to use the ".*" and the "&::" operators:
class A;
class B;
typedef void (B::*EventFunction)(int nEvent)
and then:
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne(B* delegate) { ((*delegate).*handler)(1); } // note: ".*"
};
class B
{
private:
A a;
public:
B() { a.SetEvent(&B::EventFromA); } // note: "&::"
void EventFromA(int nEvent) { /* do stuff */ }
};
Run away from raw C++ function pointers, and use std::function instead.
You can use boost::function if you are using an old compiler such as visual studio 2008 which has no support for C++11.
boost:function and std::function are the same thing - they pulled quite a bit of boost stuff into the std library for C++11.
Note: you may want to read the boost function documentation instead of the microsoft one as it's easier to understand
I highly recommend Don Clugston's excellent FastDelegate library. It provides all the things you'd expect of a real delegate and compiles down to a few ASM instructions in most cases. The accompanying article is a good read on member function pointers as well.
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
You may find C++ FAQ by Marshall Cline helpful to what you're trying to accomplish.
Read about pointers to members.
To call a method on the derived class, the method has to be declared in the base class as virtual and overriden in the base class and your pointer should point to the base class method. More about pointers to virtual members.
If you're interfacing with a C library, then you can't use a class member function without using something like boost::bind. Most C libraries that take a callback function usually also allow you to pass an extra argument of your choosing (usually of type void*), which you can use to bootstrap your class, as so:
class C
{
public:
int Method1(void) { return 3; }
int Method2(void) { return x; }
int x;
};
// This structure will hold a thunk to
struct CCallback
{
C *obj; // Instance to callback on
int (C::*callback)(void); // Class callback method, taking no arguments and returning int
};
int CBootstrapper(CCallback *pThunk)
{
// Call the thunk
return ((pThunk->obj) ->* (pThunk->callback))( /* args go here */ );
}
void DoIt(C *obj, int (C::*callback)(void))
{
// foobar() is some C library function that takes a function which takes no arguments and returns int, and it also takes a void*, and we can't change it
struct CCallback thunk = {obj, callback};
foobar(&CBootstrapper, &thunk);
}
int main(void)
{
C c;
DoIt(&c, &C::Method1); // Essentially calls foobar() with a callback of C::Method1 on c
DoIt(&c, &C::Method2); // Ditto for C::Method2
}
Unfortunately, the EventFunction type cannot point to a function of B, because it is not the correct type. You could make it the correct type, but that probably isn't really the solution you want:
typedef void (*B::EventFunction)(int nEvent);
... and then everything works once you call the callback with an obhect of B. But you probably want to be able to call functions outside of B, in other classes that do other things. That is sort of the point of a callback. But now this type points to something definitely in B. More attractive solutions are:
Make B a base class, then override a virtual function for each other class that might be called. A then stores a pointer to B instead of a function pointer. Much cleaner.
If you don't want to bind the function to a specific class type, even a base class (and I wouldn't blame you), then I suggest you make the function that gets called a static function: "static void EventFrom A(int nEvent);". Then you can call it directly, without an object of B. But you probably want it to call a specific instance of B (unless B is a singleton).
So if you want to be able to call a specific instance of B, but be able to call non-B's, too, then you need to pass something else to your callback function so that the callback function can call the right object. Make your function a static, as above, and add a void* parameter which you will make a pointer to B.
In practice you see two solutions to this problem: ad hoc systems where you pass a void* and the event, and hierarchies with virtual functions in a base class, like windowing systems
You mention that boost isn't an option for you, but do you have TR1 available to you?
TR1 offers function, bind, and mem_fn objects based on the boost library, and you may already have it bundled with your compiler. It isn't standard yet, but at least two compilers that I've used recently have had it.
http://en.wikipedia.org/wiki/Technical_Report_1
http://msdn.microsoft.com/en-us/library/bb982702.aspx
It's somewhat unclear what you're trying to accomplish here. what is clear is that function pointers is not the way.
maybe what you're looking for is pointer to method.
I have a set of classes for this exact thing that I use in my c++ framework.
http://code.google.com/p/kgui/source/browse/trunk/kgui.h
How I handle it is each class function that can be used as a callback needs a static function that binds the object type to it. I have a set of macros that do it automatically. It makes a static function with the same name except with a "CB_" prefix and an extra first parameter which is the class object pointer.
Checkout the Class types kGUICallBack and various template versions thereof for handling different parameters combinations.
#define CALLBACKGLUE(classname , func) static void CB_ ## func(void *obj) {static_cast< classname *>(obj)->func();}
#define CALLBACKGLUEPTR(classname , func, type) static void CB_ ## func(void *obj,type *name) {static_cast< classname *>(obj)->func(name);}
#define CALLBACKGLUEPTRPTR(classname , func, type,type2) static void CB_ ## func(void *obj,type *name,type2 *name2) {static_cast< classname *>(obj)->func(name,name2);}
#define CALLBACKGLUEPTRPTRPTR(classname , func, type,type2,type3) static void CB_ ## func(void *obj,type *name,type2 *name2,type3 *name3) {static_cast< classname *>(obj)->func(name,name2,name3);}
#define CALLBACKGLUEVAL(classname , func, type) static void CB_ ## func(void *obj,type val) {static_cast< classname *>(obj)->func(val);}