Executing bound std::function throws std::bad_function_call - c++

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...
}

Related

Dynamically create a function and get a pointer

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 :)

c++ save class templated function pointer inside map

I'm having a small problem which I can't wrap my head around.
I have a function that looks like this:
template <typename T>
std::unique_ptr<Environment>& CreateEnvironment(sf::Vector2f& _position, bool _addToStatic = false);
This is my function pointer typedef
typedef std::unique_ptr<Environment>& (WorldEditor::*CreateEnvironmentPtr)(sf::Vector2f&, bool);
std::map<std::string,CreateEnvironmentPtr> listEnv;
And I'm trying to simply do this:
listEnv["test"] = &CreateEnvironment<Coin>(sf::Vector2f(200,200), false);
And i get the following error:
error C2440: '=' : cannot convert from 'std::unique_ptr<_Ty> *' to
'std::unique_ptr<_Ty> &(__thiscall WorldEditor::* )(sf::Vector2f
&,bool)'
I understand what the error is saying, but I don't know how to solve it. Also why does it even care about the return type when I'm pointing to the address of the function?
Best regards
nilo
problems such as these are often much better solved with std::function
std::map<std::string, std::function<void()> listEnv;
listEnv.emplace("test", [] {
CreateEnvironment<Coin>(sf::Vector2f(200,200), false);
});
to call:
listEnv.at("test")->second();
Based on your post I am not sure if you are attempting to create the member function pointer and map inside the CreateEnvironment class or outside of it, so I'll solve what I think is the more difficult problem of pointer to a separate object's member function.
I simplified your classes like so:
Environment
struct Environment
{
int i = 1;
};
Coin
struct Coin
{
int k = 0;
};
WorldEditor
struct WorldEditor
{
template <typename T>
std::unique_ptr<Environment> CreateEnvironment(int& _j, bool _addToStatic = false)
{
return std::make_unique<Environment>();
}
};
Solution: Map an object's member fn pointer, and then call it later
(I will be using C++11/14 syntax in my answer)
//declare a pointer to member function in WorldEditor
using CreateEnvironmentPtr = std::unique_ptr<Environment> (WorldEditor::*)(int&, bool);
//declare an object of type WorldEditor, because member function pointers need a "this" pointer
WorldEditor myWorldEditor;
int myInt = 42;
//map a string to the CreateEnvironment<Coin> function
std::map<std::string, CreateEnvironmentPtr> listEnv;
listEnv["test"] = &WorldEditor::CreateEnvironment<Coin>;
// call the member function pointer using the instance I created, as well as
// the mapped function
(myWorldEditor.*listEnv["test"])(myInt, false);
// (printing member value to cout to show it worked)
std::cout << (myWorldEditor.*listEnv["test"])(myInt, false)->i << std::endl; // prints 1
Live Demo
Solution 2: use std::bind and std::function
Perhaps we already know the parameters to the member function call at the time we create the entry for map. Using std::bind with a std::function will help us achieve that (Similar to Richard Hodges' solution):
// now our "function pointer" is really just a std::function that takes no arguments
using CreateEnvironmentPtr = std::function<std::unique_ptr<Environment>(void)>;
//declare an object of type WorldEditor, because member function pointers need a "this" pointer
WorldEditor myWorldEditor;
int myInt = 42;
//map a string to that function pointer
//ensure it gets called with the right args
// by using std::bind (which will also make the arg list appear the be void at call time)
// note that std::bind needs an instance of the class immediately after
// listing the function it should be binding
// only afterwards will we then pass the int& and bool
std::map<std::string, CreateEnvironmentPtr> listEnv;
listEnv["test"] = std::bind(&WorldEditor::CreateEnvironment<Coin>, &myWorldEditor, myInt, false);
// the mapped function
listEnv["test"]()->i;
// (printing resulting unique_ptr<Environment>'s member to cout to show it worked)
std::cout << listEnv["test"]()->i << std::endl; // prints 1
Live Demo 2

Callback to a non-static C++ Member Function

I would like someone to shed some light this code snippet, which confuses me.
//-------------------------------------------------------------------------------
// 3.5 Example B: Callback to member function using a global variable
// Task: The function 'DoItB' does something that implies a callback to
// the member function 'Display'. Therefore the wrapper-function
// 'Wrapper_To_Call_Display is used.
#include <iostream.h> // due to: cout
void* pt2Object; // global variable which points to an arbitrary object
class TClassB
{
public:
void Display(const char* text) { cout << text << endl; };
static void Wrapper_To_Call_Display(char* text);
/* more of TClassB */
};
// static wrapper-function to be able to callback the member function Display()
void TClassB::Wrapper_To_Call_Display(char* string)
{
// explicitly cast global variable <pt2Object> to a pointer to TClassB
// warning: <pt2Object> MUST point to an appropriate object!
TClassB* mySelf = (TClassB*) pt2Object;
// call member
mySelf->Display(string);
}
// function does something that implies a callback
// note: of course this function can also be a member function
void DoItB(void (*pt2Function)(char* text))
{
/* do something */
pt2Function("hi, i'm calling back using a global ;-)"); // make callback
}
// execute example code
void Callback_Using_Global()
{
// 1. instantiate object of TClassB
TClassB objB;
// 2. assign global variable which is used in the static wrapper function
// important: never forget to do this!!
pt2Object = (void*) &objB;
// 3. call 'DoItB' for <objB>
DoItB(TClassB::Wrapper_To_Call_Display);
}
Question 1: Regarding this function call:
DoItB(TClassB::Wrapper_To_Call_Display)
Why does Wrapper_To_Call_Display not take any arguments, although it is supposed to take a char* argument according to its declaration?
Question 2: DoItB is declared as
void DoItB(void (*pt2Function)(char* text))
What I’ve understood so far is that DoItB takes a function pointer as argument, but why does the function call DoItB(TClassB::Wrapper_To_Call_Display) take TClassB::Wrapper_To_Call_Display as argument even tough it’s not a pointer?
Thanx in advance
Source of code snippet: http://www.newty.de/fpt/callback.html
In C/C++ when a function name is used with no parameters - that is no parenthesis - it is a pointer to a function. So TClassB::Wrapper_To_Call_Display is a pointer to the address in memory where the code for the function is implemented.
Since TClassB::Wrapper_To_Call_Display is a pointer to a void function that takes a single char* it's time is void (*)(char* test) so it matches the type required by DoItB.

std::map, storing pointer (to object) by pointer (to some object's related struct). Which types to use?

To overcome the impossibility of giving C library a callback to C++ member function, wanted to implement something like this:
SomeObject* findSomeObjectByHandlePointer(datahandle *dh) { }..
by using a map, which contains addresses of *datahandle as an index, and addresses of *SomeObject's as value.
When SomeObject is created, it produces a group of datahandle's, which are unique for the object. Then, it passes a pointer to *datahandle and static callback function to C library, then C library calls back and returns a pointer to datahandle, that in turn can be associated back with a SomeObject.
Which types can you recommend for storing pointer values in a map besides safe but slow <string, SomeObject*>?
This answer tells me to avoid using auto_ptr too.
Normally, C-like callbacks take a void* user_data parameter, which allows you to pass in anything you want:
void c_func(void (*fptr)(void*), void* user_data){
// do some stuff
fptr(user_data);
}
Now, simply make the following static member function:
class A{
public:
static void c_callback(void* my_data){
A* my_this = static_cast<A*>(my_data);
// do stuff with my_this
}
};
Edit: According to #Martin's comment, you may get unlucky with a static member function. Better use an extern "C" function:
extern "C" void c_callback(void* my_data){
// same as static method
}
And pass that + your A instance to that c_func:
int main(){
A a;
c_func(&A::c_callback,&a);
}
Or if that A instance needs to outlive the current scope, you need to somehow save the heap-allocated pointer somewhere and delete it manually later on. A shared_ptr or the likes won't work here, sadly. :(
On your problem of storing pointer in a map, that's not a problem at all, see this little example on Ideone.
I think this will suffice. It is what we use:
class datahandle;
class SomeObject;
typedef std::map<datahandle*, SomeObject*> pointer_map;
pointer_map my_map;
SomeObject* findSomeObjectByHandlePointer( datahandle *dh) {
pointer_map::const_iterator ff = my_map.find(dh);
if (ff != my_map.end()) {
return ii->second;
}
return NULL;
}
Often callback functions have an extra parameter of type void* which you can use to pass in any additional data you might need. So if you want to use a member function as your callback, you pass in a pointer to the object casted to void* and then cast it back and call the member function in your callback function.
If you have many reads and less writes, you could use vector as a set. It is very common, because lower_bound is more effective than map and use less space from memory:
typedef std::pair<std::string,Your_pointer> your_type;
bool your_less_function( const your_type &a, const your_type &b )
{
// your less function
return ( a < b );
}
...
std::vector<your_type> ordered-vector;
When you add values:
...
ordered-vector.push_back(value)
...
// Finally. The vector must be sorted before read.
std::sort( ordered-vector.begin(), ordered-vector.end(), your_less_function );
When ask for data:
std::vector<your_type>::iterator iter = std::lower_bound( ordered-vector.begin(), ordered-vector.end(), value, your_less_function );
if ( ( iter == ordered-vector.end() ) || your_less_function( *iter, value ) )
// you did not find the value
else
// iter contains the value

was not declared in this scope C++

Why do I get this error in the code below?
class ST : public Instruction{
public:
ST (string _name, int _value):Instruction(_name,_value){}
void execute(int[]& anArr, int aVal){
//not implemented yet
cout << "im an st" <<endl;
anArr[value] = aVal;
}
virtual Instruction* Clone(){
return new ST(*this);
}
};
classes.h:81: error: ‘anArr’ was not declared in this scope
classes.h:81: error: ‘aVal’ was not declared in this scope
You have a problem with the type of the first parameter of your execute function. Read this up to know more about how to pass arrays around.
Because the type of anArr is invalid.
Also you may be interested in using a covariant return type on your clone method. I.e. it can return a pointer to ST instead of Instruction.
Try this out :
void execute(int anArr[] , int aVal)
since You cant use array of reference .
If execute() is supposed to be taking an array of integers, you should probably declare it like this:
void execute(int* anArr, int anArrLength, int aVal)
{
// ...
}
Note that there are several differences to your method:
anArr is passed in as a pointer to the start of the array. The client code can simply pass in the array variable name, as by definition this is equivalent to "a pointer to the start of the array".
anArrLength is passed in to indicate the length of the array. This is required to ensure that the execute() method doesn't access memory which is out of the bounds of the array (or what has been allocated for the array). Doing so could result in memory corruption.
You could improve the method signature above by adding a return value to indicate success or failure. This would allow the client code to detect if there have been any problems. For example:
// Returns true on success, false on failure
bool execute(int* anArr, int anArrLength, int aVal)
{
// Get "value" through whatever means necessary
// ...
if (value >= anArrLength)
{
// Out of bounds of array!
return false;
}
anArr[value] = aVal;
// Do whatever else you need to do
// ...
return true;
}