Using class member function pointers in C++ for Arduino - c++

I need to make a list of function pointers to member objects and then execute them as need be in an InterruptSubRoutine. I created a class with a virtual function to wrap all classes that need interrupts, and they will use to execute their interrupt.
I can pass these and put them in the Array, but I get an error on the line where I try to execute them saying
expression must have a (pointer-to-) function type.
Header
typedef bool (InterruptSubRoutine::*function_pointer)();
void initializeTI();
void enableTI();
void disableTI();
void procInterrupt();
void addInterrupt(bool (InterruptSubRoutine::*interrupt)());
TimerThree timerInt;
function_pointer activeInterrupts[INTERRUPT_POINTER_SIZE];
Cpp
void ::initializeTI()
{
timerInt.initialize(TIMER_INTERRUPT_PERIOD);
}
void ::procInterrupt()
{
bool empty = true;
for(int i = 0; i<INTERRUPT_POINTER_SIZE; i++)
{
if (activeInterrupts[i] != nullptr)
{
empty = false;
bool returnV = activeInterrupts[i](); //this is where i get the problem, with the error stating "expression must have a (pointer-to-) function type"
if (!returnV)
{
activeInterrupts[i] = nullptr;
}
}
}
if (empty)
{
disableTI();
}
}
void ::addInterrupt(bool (InterruptSubRoutine::*function)())
{
for(int i = 0; i<INTERRUPT_POINTER_SIZE; i++)
{
if (activeInterrupts[i] == nullptr)
{
activeInterrupts[i] = function;
break;
}
}
}
void ::enableTI()
{
void (*interrupt)(void);
interrupt = &procInterrupt;
timerInt.attachInterrupt(interrupt, TIMER_INTERRUPT_PERIOD);
}
void ::disableTI()
{
timerInt.detachInterrupt();
}

here's something to get you started:
activeInterrupts is an array of function pointers
function_pointer activeInterrupts[INTERRUPT_POINTER_SIZE]; hence activeInterrupts[i] will be a function pointer.
you can't assign a integer-type variable, a function pointer: bool returnV = activeInterrupts[i](), they are incompatible types

Your problem starts with the wording of the question:
I need to make a list of function pointers to member objects...
No! You have pointer to member functions! And member functions need a object in which they are executed.
I created a class with a virtual function to wrap all classes that need interrupts
No! You create a base class where instances from derived classes ( which are called objects ) can use the given member functions. Please remember: The methods are part of the class but they are running in the context of the object.
Instead of that you also can have static class functions which are related to the class and work without objects! This is also possible but a total different approach.
From your wording I believe you did not really understand what is class,method,object and the relations between them. So I would advice you to read a OOP beginners book.
The simple problem as result of your wrong coding is, that you need an object in which context you can call the member function ( method ) which is addressed via a member function pointer.
If you want to store a object and a pointer, simply use a struct to fill the pointer and the object in and do the call. You are also free to bind the method pointer to the object with std::bind if you are using a modern c++11 version. As std::bind is header only code from c++ it works also for avr.
In general:
I think it is a bad design for small embedded systems to create, register, and store objects and in addition pointers to functions in runtime! this all can be done during compile time which makes the code much faster, smaller and less error prone. Think about memory allocation ( new/malloc) on a small embedded device! And if you are already use static allocation and global objects ( which is also bad design in bigger projects ) you also can resolve your call tree to all objects during compile time.
As a simple fix for your first problem you should:
bool returnV = (object.*activeInterrupts[i])();
where object is an instance of InterruptSubRoutine class or any derived class from that.
As an additional remark to your question itself:
It would be nice to shrink down all code snippets to the minimum we need to analyze the problem. On the other hand it would be nice if it could be used to compile it directly without adding all the missing stuff. Thanks!

Related

A pointer to member is not valid for a managed class

I created a library in which one exposed function accepts a function pointer of type void(*fun_ptr)(int).
The function syntax is:
start_server(char *devices, char *folder, int number, int timeout, void(*status_of_server)(int));
This is working with normal C++ functions like void getStatus(int n); but when I used them in a Visual C++ environment for a GUI application, I'm getting this error:
A pointer to member is not valid for a managed class
start_server(&devs, &base, 1, 0, &TestApplication::MainWindow::StatusOfServer );
Where StatusOfServer is defined inside the MainWindow class which can be used for UI management.
private: void TestApplication::MainWindow::StatusOfServer(int n)
{
this->progressBar->Value = n;
}
What is the correct way of handling this?
The reason for the weird behavior is that each member function has implicitly appended to it's signature a pointer to it's type, e.g. :
#include <iostream>
struct S
{
int i;
void doSth() { std::cout << i << std::endl; }
};
int main()
{
S s{1};
s.doSth();
auto member_f = &S::doSth;
(s.*member_f)();
}
doSth() has a hidden parameter, so it can't be called like a regular function. In your example the situation is similar- you are trying to call member function as if it was a normal free function, which will not work. Usually in APIs requesting function pointers, the functions can take void* as parameter, which allows you to write a wrapper that will cast the pointer to the correct type and then invoke member function on the pointed to instance of the class. However from the code you've shown above, you can't pass void* into the function, so you'll have probably have some sort of global state (e.g. make that function static and let it work only on static data).
One solution would be to create a small non-managed wrapper function around the managed one:
void wrapStatusOfServer(int n) {
TestApplication::MainWindow::StatusOfServer(n)
}
and get a pointer to the wrapper
start_server(&devs, &base, 1, 0, &wrapStatusOfServer);
Another solution: turn your start_server into managed code and use a delegate instead of a function pointer: https://learn.microsoft.com/en-us/cpp/dotnet/how-to-define-and-use-delegates-cpp-cli?view=vs-2017
C++/CLI is fraught with this kind of issue, where managed and un-managed code and data are almost but not quite interoperable.

How to access a non-static member from a static member function in C++?

I wrote the following code:
class A
{
public:
int cnt;
static void inc(){
d.cnt=0;
}
};
int main()
{
A d;
return 0;
}
I have seen this question:
How to call a non static member function from a static member function without passing class instance
But I don't want to use pointer. Can I do it without using pointers?
Edit:
I have seen the following question:
how to access a non static member from a static method in java?
why can't I do something like that?
No, there is no way of calling a non-static member function from a static function without having a pointer to an object instance. How else would the compiler know what object to call the function on?
Like the others have pointed out, you need access to an object in order to perform an operation on it, including access its member variables.
You could technically write code like my zeroBad() function below. However, since you need access to the object anyway, you might as well make it a member function, like zeroGood():
class A
{
int count;
public:
A() : count(42) {}
// Zero someone else
static void zeroBad(A& other) {
other.count = 0;
}
// Zero myself
void zeroGood() {
count = 0;
}
};
int main()
{
A a;
A::zeroBad(a); // You don't really want to do this
a.zeroGood(); // You want this
}
Update:
You can implement the Singleton pattern in C++ as well. Unless you have a very specific reason you probably don't want to do that, though. Singleton is considered an anti-pattern by many, for example because it is difficult to test. If you find yourself wanting to do this, refactoring your program or redesigning is probably the best solution.
You cannot use non-static member variables or functions inside a static function without using pointers.
You don't need a pointer per se, but you do need access to the object through which you are accessing the non-static variable. In your example, the object d is not visible to A::inc(). If d were a global variable rather than a local variable of main, your example would work.
That said, it's curious why you'd want to go to any great effort to avoid using pointers in C++.

C++ member function invocation

Ok so often times I have seen the following type of event handling used:
Connect(objectToUse, MyClass::MyMemberFunction);
for some sort of event handling where objectToUse is of the type MyClass. My question is how exactly this works. How would you convert this to something that would do objectToUse->MyMemberFunction()
Does the MyClass::MyMemberFunction give an offset from the beginning of the class that can then be used as a function pointer?
In addition to Mats' answer, I'll give you a short example of how you can use a non-static member function in this type of thing. If you're not familiar with pointers to member functions, you may want to check out the FAQ first.
Then, consider this (rather simplistic) example:
class MyClass
{
public:
int Mult(int x)
{
return (x * x);
}
int Add(int x)
{
return (x + x);
}
};
int Invoke(MyClass *obj, int (MyClass::*f)(int), int x)
{ // invokes a member function of MyClass that accepts an int and returns an int
// on the object 'obj' and returns.
return obj->*f(x);
}
int main(int, char **)
{
MyClass x;
int nine = Invoke(&x, MyClass::Mult, 3);
int six = Invoke(&x, MyClass::Add, 3);
std::cout << "nine = " << nine << std::endl;
std::cout << "six = " << six << std::endl;
return 0;
}
Typically, this uses a static member function (that takes a pointer as an argument), in which case the the objectToUse is passed in as a parameter, and the MyMemberFunction would use objectToUse to set up a pointer to a MyClass object and use that to refer to member variables and member functions.
In this case Connect will contain something like this:
void Connect(void *objectToUse, void (*f)(void *obj))
{
...
f(objectToUse);
...
}
[It is also quite possible that f and objectToUse are saved away somewhere to be used later, rather than actually inside Connnect, but the call would look the same in that case too - just from some other function called as a consequence of the event that this function is supposed to be called for].
It's also POSSIBLE to use a pointer to member function, but it's quite complex, and not at all easy to "get right" - both when it comes to syntax and "when and how you can use it correctly". See more here.
In this case, Connect would look somewhat like this:
void Connect(MyClass *objectToUse, void (Myclass::*f)())
{
...
objectToUse->*f();
...
}
It is highly likely that templates are used, as if the "MyClass" is known in the Connect class, it would be pretty pointless to have a function pointer. A virtual function would be a much better choice.
Given the right circumstances, you can also use virtual functions as member function pointers, but it requires the compiler/environment to "play along". Here's some more details on that subject [which I've got no personal experience at all of: Pointers to virtual member functions. How does it work?
Vlad also points out Functors, which is an object wrapping a function, allowing for an object with a specific behaviour to be passed in as a "function object". Typically this involves a predefined member function or an operatorXX which is called as part of the processing in the function that needs to call back into the code.
C++11 allows for "Lambda functions", which is functions declared on the fly in the code, that doesn't have a name. This is something I haven't used at all, so I can't really comment further on this - I've read about it, but not had a need to use it in my (hobby) programming - most of my working life is with C, rather than C++ although I have worked for 5 years with C++ too.
I might be wrong here, but as far as I understand,
In C++, functions with the same signature are equal.
C++ member functions with n parameters are actually normal functions with n+1 parameters. In other words, void MyClass::Method( int i ) is in effect void (some type)function( MyClass *ptr, int i).
So therefore, I think the way Connect would work behind the scenes is to cast the member method signature to a normal function signature. It would also need a pointer to the instance to actually make the connection work, which is why it would need objectToUse
In other words, it would essentially be using pointers to functions and casting them to a more generic type until it can be called with the parameters supplied and the additional parameter, which is the pointer to the instance of the object
If the method is static, then a pointer to an instance doesn't make sense and its a straight type conversion. I have not figured out the intricacies involved with non-static methods yet - a look at the internals of boost::bind is probably what you want to do to understand that :) Here is how it would work for a static function.
#include <iostream>
#include <string>
void sayhi( std::string const& str )
{
std::cout<<"function says hi "<<str<<"\n";
}
struct A
{
static void sayhi( std::string const& str )
{
std::cout<<"A says hi "<<str<<"\n";
}
};
int main()
{
typedef void (*funptr)(std::string const&);
funptr hello = sayhi;
hello("you"); //function says...
hello = (&A::sayhi); //This is how Connect would work with a static method
hello("you"); //A says...
return 0;
}
For event handling or callbacks, they usually take two parameters - a callback function and a userdata argument. The callback function's signature would have userdata as one of the parameters.
The code which invokes the event or callback would invoke the function directly with the userdata argument. Something like this for example:
eventCallbackFunction(userData);
In your event handling or callback function, you can choose to use the userdata to do anything you would like.
Since the function needs to be callable directly without an object, it can either be a global function or a static method of a class (which does not need an object pointer).
A static method has limitations that it can only access static member variables and call other static methods (since it does not have the this pointer). That is where userData can be used to get the object pointer.
With all this mind, take a look at the following example code snippet:
class MyClass
{
...
public:
static MyStaticMethod(void* userData)
{
// You can access only static members here
MyClass* myObj = (MyClass*)userdata;
myObj->MyMemberMethod();
}
void MyMemberMethod()
{
// Access any non-static members here as well
...
}
...
...
};
MyClass myObject;
Connect(myObject, MyClass::MyStaticMethod);
As you can see you can access even member variables and methods as part of the event handling if you could make a static method which would be invoked first which would chain the call to a member method using the object pointer (retrieved from userData).

Help needed in Use of Function pointer in C++

i have made a sample example, in this i'm trying to pass a function as argument i am getting error, could you please help me
typedef void (*callbackptr)(int,int);
class Myfirst
{
public:
Myfirst();
~Myfirst();
void add(int i,callbackptr ptr)
{
ptr(i,3);
}
};
class Mysec
{
public:
Myfirst first_ptr;
Mysec();
~Mysec();
void TestCallback()
{
callbackptr pass_ptr = NULL;
pass_ptr = &Mysec::Testing;
first_ptr.add(2,&Mysec::Testing);
}
void Testing(int a,int b)
{
int c = a+b;
}
};
The type of the callback function you're passing as parameter is not defined as part of a class. You probably should define Testing as static.
You are geting an error because you are pointing to a member function. Pointers to member functions are different. See here:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1
A member function needs to know what instance it is working with (the this pointer) so it can't be called like any other function. If you moved the callback function out of the class (or made it static, which is similar to moving it out of the class) you could call it like any other function.
A more modern way of doing this is to use functors, e.g. boost::function and something like boost::bind :
C++ Functors - and their uses
how boost::function and boost::bind work
Those can hide the difference between member and global functions.
You are trying to access a member function pointer here, using a simple function pointer typedef, which will not work. Let me explain.
When you write a normal, non-member function (similar to C), the function's code actually exists in a location indicated by the name of the function - which you would pass to a function pointer parameter.
However, in the case of a member function, all you have is the class definition; you don't have the actual instance of the class allocated in memory yet. In such a function, since the this pointer is not yet defined, any reference to member variables wouldn't make sense, since the compiler doesn't have enough information to resolve their memory locations. In fact, member function pointers are not exact addresses; they encode more information than that (which may not be visible to you). For more, read Pointers to Member Functions.

Why would one use function pointers to member method in C++?

A lot of C++ books and tutorials explain how to do this, but I haven't seen one that gives a convincing reason to choose to do this.
I understand very well why function pointers were necessary in C (e.g., when using some POSIX facilities). However, AFAIK you can't send them a member function because of the "this" parameter. But if you're already using classes and objects, why not just use an object oriented solution like functors?
Real world examples of where you had to use such function pointers would be appreciated.
Update: I appreciate everyone's answers. I have to say, though, that none of these examples really convinces me that this is a valid mechanism from a pure-OO perspective...
Functors are not a priori object-oriented (in C++, the term “functor” usually means a struct defining an operator () with arbitrary arguments and return value that can be used as syntactical drop-in replacements to real functions or function pointers). However, their object-oriented problem has a lot of issues, first and foremost usability. It's just a whole lot of complicated boilerplate code. In order for a decent signalling framework as in most dialog frameworks, a whole lot of inheritance mess becomes necessary.
Instance-bound function pointers would be very beneficial here (.NET demonstrates this amply with delegates).
However, C++ member function pointers satisfy another need still. Imagine, for example, that you've got a lot of values in a list of which you want to execute one method, say its print(). A function pointer to YourType::size helps here because it lets you write such code:
std::for_each(lst.begin(), lst.end(), std::mem_fun(&YourType::print))
In the past, member function pointers used to be useful in scenarios like this:
class Image {
// avoid duplicating the loop code
void each(void(Image::* callback)(Point)) {
for(int x = 0; x < w; x++)
for(int y = 0; y < h; y++)
callback(Point(x, y));
}
void applyGreyscale() { each(&Image::greyscalePixel); }
void greyscalePixel(Point p) {
Color c = pixels[p];
pixels[p] = Color::fromHsv(0, 0, (c.r() + c.g() + c.b()) / 3);
}
void applyInvert() { each(&Image::invertPixel); }
void invertPixel(Point p) {
Color c = pixels[p];
pixels[p] = Color::fromRgb(255 - c.r(), 255 - r.g(), 255 - r.b());
}
};
I've seen that used in a commercial painting app. (interestingly, it's one of the few C++ problems better solved with the preprocessor).
Today, however, the only use for member function pointers is inside the implementation of boost::bind.
Here is a typical scenario we have here. We have a notification framework, where a class can register to multiple different notifications. When registering to a notification, we pass the member function pointer. This is actually very similar to C# events.
class MyClass
{
MyClass()
{
NotificationMgr::Register( FunctionPtr( this, OnNotification ) );
}
~MyClass()
{
NotificationMgr::UnRegister( FunctionPtr( this, OnNotification ) );
}
void OnNotification( ... )
{
// handle notification
}
};
I have some code I'm working on right now where I used them to implement a state machine. The dereferenced member functions implement the states, but since they are all in the class they get to share a certian amount of data that is global to the entire state machine. That would have been tough to accomplish with normal (non-member) function pointers.
I'm still undecided on if this is a good way to implement a state machine though.
It is like using lambdas. You always can pass all necessary local variables to a simple function, but sometimes you have to pass more then one of them.
So using member functions will save you from passing all necessary member fields to a functor. That's all.
You asked specifically about member functions, but there are other uses for function pointers as well. The most common reason why I need to use function pointers in C++ is when I want to load a DLL ar runtime using LoadLibrary(). This is in Windows, obviously. In applications that use plugins in the form of optional DLLs, dynamic linking can't be used at application startup since the DLL will often not be present, and using delayload is a pain.
After loading the library, you have to get a pointer to the functions you want to use.
I have used member function pointers parsing a file. Depending on specific strings found in the file the same value was found in a map and the associated function called. This was instead of a large if..else if..else statement comparing strings.
The single most important use of member pointers is creating functors. The good news is that you hardly even need to use it directly, as it is already solved in libraries as boost::bind, but you do have to pass the pointers to those libs.
class Processor
{
public:
void operation( int value );
void another_operation( int value );
};
int main()
{
Processor tc;
boost::thread thr1( boost::bind( &Processor::operation, &tc, 100 ) );
boost::thread thr2( boost::bind( &Processor::another_operation, &tc, 5 ) );
thr1.join();
thr2.join();
}
You can see the simplicity of creating a thread that executes a given operation on a given instance of a class.
The simple handmade approach to the problem above would be on the line of creating a functor yourself:
class functor1
{
public:
functor1( Processor& o, int v ) : o_(o), v_(v) {}
void operator()() {
o_.operation( v_ ); // [1]
}
private:
Processor& o_;
int v_;
};
and create a different one for each member function you wish to call. Note that the functor is exactly the same for operation and for another_operation, but the call in [1] would have to be replicated in both functors. Using a member function pointer you can write a simple functor:
class functor
{
public:
functor( void (*Processor::member)(int), Processor& p, int value )
: member_( member ), processor_(p), value_( value ) {}
void operator()() {
p.*member(value_);
}
private:
void (*Processor::member_)(int);
Processor& processor_;
int value;
};
and use it:
int main() {
Processor p;
boost::thread thr1( functor( &Processor::operation, p, 100 ) );
boost::thread thr2( functor( &Processor::another_operation, p, 5 ) );
thr1.join();
thr2.join();
}
Then again, you don't need to even define that functor as boost::bind does it for you. The upcoming standard will have its own version of bind along the lines of boost's implementation.
A pointer to a member function is object-agnostic. You need it if you want to refer to a function by value at run-time (or as a template parameter). It comes into its own when you don't have a single object in mind upon which to call it.
So if you know the function, but don't know the object AND you wish to pass this knowledge by value, then point-to-member-function is the only prescribed solution. Iraimbilanja's example illustrates this well. It may help you to see my example use of a member variable. The principle is the same.
I used a function pointer to a member function in a scenario where I had to provide a function pointer to a callback with a predefined parameter list (so I couldn't pass arbitrary parameters) to some 3rd-party API object.
I could not implement the callback in the global namespace because it was supposed to handle incoming events based on state of the object which made use of the 3rd party API which had triggered the callback.
So I wanted the implementation of the callback to be part of the class which made use of the 3rd-party object. What I did is, I declared a public and static member function in the class I wanted to implement the callback in and passed a pointer to it to the API object (the static keyword sparing me the this pointer trouble).
The this pointer of my object would then be passed as part of the Refcon for the callback (which luckily contained a general purpose void*).
The implementation of the dummy then used the passed pointer to invoke the actual, and private, implementation of the callback contained in the class = ).
It looked something like this:
public:
void SomeClass::DummyCallback( void* pRefCon ) [ static ]
{
reinterpret_cast<SomeClassT*>(pRefCon)->Callback();
}
private:
void class SomeClass::Callback() [ static ]
{
// some code ...
}