Passing function pointer point to member method [duplicate] - c++

The question is the following: consider this piece of code:
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass a;
function1(&test);
function1(&aClass::aTest); // <-- How should I point to a's aClass::test function?
}
How can I use the a's aClass::test as an argument to function1? I would like to access a member of the class.

There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus
void (aClass::*)(int, int)
rather than the type you try to use
void (*)(int, int)
One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).
If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.
In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().
The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.
To clarify how to use a function pointer to call a member function, here is an example:
// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
fptr(context, 17, 42);
}
void non_member(void*, int i0, int i1) {
std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}
struct foo {
void member(int i0, int i1) {
std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
}
};
void forwarder(void* context, int i0, int i1) {
static_cast<foo*>(context)->member(i0, i1);
}
int main() {
somefunction(&non_member, nullptr);
foo object;
somefunction(&forwarder, &object);
}

#Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:
#include <functional>
using namespace std::placeholders;
void function1(std::function<void(int, int)> fun)
{
fun(1, 1);
}
int main (int argc, const char * argv[])
{
...
aClass a;
auto fp = std::bind(&aClass::test, a, _1, _2);
function1(fp);
return 0;
}

A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be
void function1(void (aClass::*function)(int, int), aClass& a) {
(a.*function)(1, 1);
}
and to call it:
aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);

Since 2011, if you can change function1, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
(live demo)
Notice also that I fixed your broken object definition (aClass a(); declares a function).

I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference

Important to note that unless you can change the signature of the code taking the function, there is no (easy) way to do this. That would be trying to implement a closure in a language that does not have closures that are the same as functions (the signature for a closure in C++ is different).
There are two actual ways to achieve this:
Use some sort of singleton/global variable that you store the closure in, and then pass a helper function that calls the needed function using that closure. Here is an example:
#include <stdio.h>
template<class C, typename ReturnType, typename... Args>
class ClosureSingleton {
typedef ReturnType (C::*FuncType)(Args...);
public:
static ClosureSingleton& getInstance() {
static ClosureSingleton instance;
return instance;
}
void setClosure(C* obj, FuncType f) {
this->obj = obj;
this->function = f;
}
static ReturnType funcPtr(Args... args) {
C* obj = getInstance().obj;
auto func = getInstance().function;
return (obj->*func)(args...);
}
private:
ClosureSingleton() {}
C* obj;
FuncType function;
public:
ClosureSingleton(ClosureSingleton const&) = delete;
void operator=(ClosureSingleton const&) = delete;
};
class aClass {
public:
void aTest1(int a, int b) { printf("%d + %d = %d\n", a, b, a + b); }
int aTest2(int a, int b) { return a + b; }
};
void function1(void (*function)(int, int)) {
function(1, 1);
}
int function2(int (*function)(int, int)) {
return function(1, 1);
}
int main() {
aClass tmp;
ClosureSingleton<aClass, void, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest1);
function1(&ClosureSingleton<aClass, void, int, int>::funcPtr);
ClosureSingleton<aClass, int, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest2);
printf(
"function2: %d\n",
function2(&ClosureSingleton<aClass, int, int, int>::funcPtr));
return 0;
}
Of course, this has the obvious downside that the closure needs to be set before every call, as well as some thread safety issues. Not ideal, but potentially workable in specific circumstances
Use something like asmjit or dynamic compilation to dynamically compile and pass the function in to the C code. This will only work on machines that allow heap section to be marked as executable. It is also very much non-portable as you will be writing assembly code to accomplish this. However, if you get it working, you will indeed have a true closure, albeit a substantially higher cost to creating the closure compared to how most programming languages implement closures (they do not duplicate the function assembly, instead they use a context object)
Patch the lib/dll that has the function handler to change it's signature to allow a context object. Again, a very brittle and non optimal solution.
My original answer, which does not really answer the question, but people found it useful:
Not sure why this incredibly simple solution has been passed up:
#include <stdio.h>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
template<class C>
void function1(void (C::*function)(int, int), C& c)
{
(c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(&test);
function1<aClass>(&aClass::aTest, a);
return 0;
}
Output:
1 - 1 = 0
1 + 1 = 2

I made the member function as static and all works:
#include <iostream>
class aClass
{
public:
static void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
void function1(int a,int b,void function(int, int))
{
function(a, b);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(10,12,test);
function1(10,12,a.aTest); // <-- How should I point to a's aClass::test function?
getchar();return 0;
}

If you actually don't need to use the instance a
(i.e. you can make it static like #mathengineer 's answer)
you can simply pass in a non-capture lambda. (which decay to function pointer)
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
int main()
{
//note: you don't need the `+`
function1(+[](int a,int b){return aClass{}.aTest(a,b);});
}
Wandbox
note: if aClass is costly to construct or has side effect, this may not be a good way.

You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.
http://cpp.sh/9jhk3
// Example program
#include <iostream>
#include <string>
using namespace std;
typedef int FooCooker_ (int);
// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
cout << "Cooking 10 Foo ..." << endl;
cout << "FooCooker:" << endl;
FooCooker (10);
}
struct Bar_ {
Bar_ (int Foo = 0) : Foo (Foo) {};
int cook (int Foo) {
cout << "This Bar got " << this->Foo << endl;
if (this->Foo >= Foo) {
this->Foo -= Foo;
cout << Foo << " cooked" << endl;
return Foo;
} else {
cout << "Can't cook " << Foo << endl;
return 0;
}
}
int Foo = 0;
};
// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* Bar1Ptr = NULL;
static int cook_in_Bar1 (int Foo) {
return Bar1Ptr->cook (Foo);
}
thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
return Bar2Ptr->cook (Foo);
}
int main () {
Bar1Ptr = new Bar_ (20);
cook_10_foo (cook_in_Bar1);
Bar2Ptr = new Bar_ (40);
cook_10_foo (cook_in_Bar2);
delete Bar1Ptr;
delete Bar2Ptr;
return 0;
}
Please comment on any issues with this approach.
Other answers fail to call existing plain C functions: http://cpp.sh/8exun

Related

Refactoring with AceButton Library causing "Invalid use of Non-Static member function" on compile [duplicate]

The question is the following: consider this piece of code:
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass a;
function1(&test);
function1(&aClass::aTest); // <-- How should I point to a's aClass::test function?
}
How can I use the a's aClass::test as an argument to function1? I would like to access a member of the class.
There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus
void (aClass::*)(int, int)
rather than the type you try to use
void (*)(int, int)
One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).
If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.
In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().
The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.
To clarify how to use a function pointer to call a member function, here is an example:
// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
fptr(context, 17, 42);
}
void non_member(void*, int i0, int i1) {
std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}
struct foo {
void member(int i0, int i1) {
std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
}
};
void forwarder(void* context, int i0, int i1) {
static_cast<foo*>(context)->member(i0, i1);
}
int main() {
somefunction(&non_member, nullptr);
foo object;
somefunction(&forwarder, &object);
}
#Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:
#include <functional>
using namespace std::placeholders;
void function1(std::function<void(int, int)> fun)
{
fun(1, 1);
}
int main (int argc, const char * argv[])
{
...
aClass a;
auto fp = std::bind(&aClass::test, a, _1, _2);
function1(fp);
return 0;
}
A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be
void function1(void (aClass::*function)(int, int), aClass& a) {
(a.*function)(1, 1);
}
and to call it:
aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);
Since 2011, if you can change function1, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
(live demo)
Notice also that I fixed your broken object definition (aClass a(); declares a function).
I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference
Important to note that unless you can change the signature of the code taking the function, there is no (easy) way to do this. That would be trying to implement a closure in a language that does not have closures that are the same as functions (the signature for a closure in C++ is different).
There are two actual ways to achieve this:
Use some sort of singleton/global variable that you store the closure in, and then pass a helper function that calls the needed function using that closure. Here is an example:
#include <stdio.h>
template<class C, typename ReturnType, typename... Args>
class ClosureSingleton {
typedef ReturnType (C::*FuncType)(Args...);
public:
static ClosureSingleton& getInstance() {
static ClosureSingleton instance;
return instance;
}
void setClosure(C* obj, FuncType f) {
this->obj = obj;
this->function = f;
}
static ReturnType funcPtr(Args... args) {
C* obj = getInstance().obj;
auto func = getInstance().function;
return (obj->*func)(args...);
}
private:
ClosureSingleton() {}
C* obj;
FuncType function;
public:
ClosureSingleton(ClosureSingleton const&) = delete;
void operator=(ClosureSingleton const&) = delete;
};
class aClass {
public:
void aTest1(int a, int b) { printf("%d + %d = %d\n", a, b, a + b); }
int aTest2(int a, int b) { return a + b; }
};
void function1(void (*function)(int, int)) {
function(1, 1);
}
int function2(int (*function)(int, int)) {
return function(1, 1);
}
int main() {
aClass tmp;
ClosureSingleton<aClass, void, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest1);
function1(&ClosureSingleton<aClass, void, int, int>::funcPtr);
ClosureSingleton<aClass, int, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest2);
printf(
"function2: %d\n",
function2(&ClosureSingleton<aClass, int, int, int>::funcPtr));
return 0;
}
Of course, this has the obvious downside that the closure needs to be set before every call, as well as some thread safety issues. Not ideal, but potentially workable in specific circumstances
Use something like asmjit or dynamic compilation to dynamically compile and pass the function in to the C code. This will only work on machines that allow heap section to be marked as executable. It is also very much non-portable as you will be writing assembly code to accomplish this. However, if you get it working, you will indeed have a true closure, albeit a substantially higher cost to creating the closure compared to how most programming languages implement closures (they do not duplicate the function assembly, instead they use a context object)
Patch the lib/dll that has the function handler to change it's signature to allow a context object. Again, a very brittle and non optimal solution.
My original answer, which does not really answer the question, but people found it useful:
Not sure why this incredibly simple solution has been passed up:
#include <stdio.h>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
template<class C>
void function1(void (C::*function)(int, int), C& c)
{
(c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(&test);
function1<aClass>(&aClass::aTest, a);
return 0;
}
Output:
1 - 1 = 0
1 + 1 = 2
I made the member function as static and all works:
#include <iostream>
class aClass
{
public:
static void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
void function1(int a,int b,void function(int, int))
{
function(a, b);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(10,12,test);
function1(10,12,a.aTest); // <-- How should I point to a's aClass::test function?
getchar();return 0;
}
If you actually don't need to use the instance a
(i.e. you can make it static like #mathengineer 's answer)
you can simply pass in a non-capture lambda. (which decay to function pointer)
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
int main()
{
//note: you don't need the `+`
function1(+[](int a,int b){return aClass{}.aTest(a,b);});
}
Wandbox
note: if aClass is costly to construct or has side effect, this may not be a good way.
You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.
http://cpp.sh/9jhk3
// Example program
#include <iostream>
#include <string>
using namespace std;
typedef int FooCooker_ (int);
// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
cout << "Cooking 10 Foo ..." << endl;
cout << "FooCooker:" << endl;
FooCooker (10);
}
struct Bar_ {
Bar_ (int Foo = 0) : Foo (Foo) {};
int cook (int Foo) {
cout << "This Bar got " << this->Foo << endl;
if (this->Foo >= Foo) {
this->Foo -= Foo;
cout << Foo << " cooked" << endl;
return Foo;
} else {
cout << "Can't cook " << Foo << endl;
return 0;
}
}
int Foo = 0;
};
// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* Bar1Ptr = NULL;
static int cook_in_Bar1 (int Foo) {
return Bar1Ptr->cook (Foo);
}
thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
return Bar2Ptr->cook (Foo);
}
int main () {
Bar1Ptr = new Bar_ (20);
cook_10_foo (cook_in_Bar1);
Bar2Ptr = new Bar_ (40);
cook_10_foo (cook_in_Bar2);
delete Bar1Ptr;
delete Bar2Ptr;
return 0;
}
Please comment on any issues with this approach.
Other answers fail to call existing plain C functions: http://cpp.sh/8exun

How can I pass a function as a parameter in C++? [duplicate]

The question is the following: consider this piece of code:
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass a;
function1(&test);
function1(&aClass::aTest); // <-- How should I point to a's aClass::test function?
}
How can I use the a's aClass::test as an argument to function1? I would like to access a member of the class.
There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus
void (aClass::*)(int, int)
rather than the type you try to use
void (*)(int, int)
One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).
If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.
In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().
The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.
To clarify how to use a function pointer to call a member function, here is an example:
// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
fptr(context, 17, 42);
}
void non_member(void*, int i0, int i1) {
std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}
struct foo {
void member(int i0, int i1) {
std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
}
};
void forwarder(void* context, int i0, int i1) {
static_cast<foo*>(context)->member(i0, i1);
}
int main() {
somefunction(&non_member, nullptr);
foo object;
somefunction(&forwarder, &object);
}
#Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:
#include <functional>
using namespace std::placeholders;
void function1(std::function<void(int, int)> fun)
{
fun(1, 1);
}
int main (int argc, const char * argv[])
{
...
aClass a;
auto fp = std::bind(&aClass::test, a, _1, _2);
function1(fp);
return 0;
}
A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be
void function1(void (aClass::*function)(int, int), aClass& a) {
(a.*function)(1, 1);
}
and to call it:
aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);
Since 2011, if you can change function1, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
(live demo)
Notice also that I fixed your broken object definition (aClass a(); declares a function).
I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference
Important to note that unless you can change the signature of the code taking the function, there is no (easy) way to do this. That would be trying to implement a closure in a language that does not have closures that are the same as functions (the signature for a closure in C++ is different).
There are two actual ways to achieve this:
Use some sort of singleton/global variable that you store the closure in, and then pass a helper function that calls the needed function using that closure. Here is an example:
#include <stdio.h>
template<class C, typename ReturnType, typename... Args>
class ClosureSingleton {
typedef ReturnType (C::*FuncType)(Args...);
public:
static ClosureSingleton& getInstance() {
static ClosureSingleton instance;
return instance;
}
void setClosure(C* obj, FuncType f) {
this->obj = obj;
this->function = f;
}
static ReturnType funcPtr(Args... args) {
C* obj = getInstance().obj;
auto func = getInstance().function;
return (obj->*func)(args...);
}
private:
ClosureSingleton() {}
C* obj;
FuncType function;
public:
ClosureSingleton(ClosureSingleton const&) = delete;
void operator=(ClosureSingleton const&) = delete;
};
class aClass {
public:
void aTest1(int a, int b) { printf("%d + %d = %d\n", a, b, a + b); }
int aTest2(int a, int b) { return a + b; }
};
void function1(void (*function)(int, int)) {
function(1, 1);
}
int function2(int (*function)(int, int)) {
return function(1, 1);
}
int main() {
aClass tmp;
ClosureSingleton<aClass, void, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest1);
function1(&ClosureSingleton<aClass, void, int, int>::funcPtr);
ClosureSingleton<aClass, int, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest2);
printf(
"function2: %d\n",
function2(&ClosureSingleton<aClass, int, int, int>::funcPtr));
return 0;
}
Of course, this has the obvious downside that the closure needs to be set before every call, as well as some thread safety issues. Not ideal, but potentially workable in specific circumstances
Use something like asmjit or dynamic compilation to dynamically compile and pass the function in to the C code. This will only work on machines that allow heap section to be marked as executable. It is also very much non-portable as you will be writing assembly code to accomplish this. However, if you get it working, you will indeed have a true closure, albeit a substantially higher cost to creating the closure compared to how most programming languages implement closures (they do not duplicate the function assembly, instead they use a context object)
Patch the lib/dll that has the function handler to change it's signature to allow a context object. Again, a very brittle and non optimal solution.
My original answer, which does not really answer the question, but people found it useful:
Not sure why this incredibly simple solution has been passed up:
#include <stdio.h>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
template<class C>
void function1(void (C::*function)(int, int), C& c)
{
(c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(&test);
function1<aClass>(&aClass::aTest, a);
return 0;
}
Output:
1 - 1 = 0
1 + 1 = 2
I made the member function as static and all works:
#include <iostream>
class aClass
{
public:
static void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
void function1(int a,int b,void function(int, int))
{
function(a, b);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(10,12,test);
function1(10,12,a.aTest); // <-- How should I point to a's aClass::test function?
getchar();return 0;
}
If you actually don't need to use the instance a
(i.e. you can make it static like #mathengineer 's answer)
you can simply pass in a non-capture lambda. (which decay to function pointer)
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
int main()
{
//note: you don't need the `+`
function1(+[](int a,int b){return aClass{}.aTest(a,b);});
}
Wandbox
note: if aClass is costly to construct or has side effect, this may not be a good way.
You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.
http://cpp.sh/9jhk3
// Example program
#include <iostream>
#include <string>
using namespace std;
typedef int FooCooker_ (int);
// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
cout << "Cooking 10 Foo ..." << endl;
cout << "FooCooker:" << endl;
FooCooker (10);
}
struct Bar_ {
Bar_ (int Foo = 0) : Foo (Foo) {};
int cook (int Foo) {
cout << "This Bar got " << this->Foo << endl;
if (this->Foo >= Foo) {
this->Foo -= Foo;
cout << Foo << " cooked" << endl;
return Foo;
} else {
cout << "Can't cook " << Foo << endl;
return 0;
}
}
int Foo = 0;
};
// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* Bar1Ptr = NULL;
static int cook_in_Bar1 (int Foo) {
return Bar1Ptr->cook (Foo);
}
thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
return Bar2Ptr->cook (Foo);
}
int main () {
Bar1Ptr = new Bar_ (20);
cook_10_foo (cook_in_Bar1);
Bar2Ptr = new Bar_ (40);
cook_10_foo (cook_in_Bar2);
delete Bar1Ptr;
delete Bar2Ptr;
return 0;
}
Please comment on any issues with this approach.
Other answers fail to call existing plain C functions: http://cpp.sh/8exun

Cast function pointer from a C++ class to use it in C [duplicate]

The question is the following: consider this piece of code:
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass a;
function1(&test);
function1(&aClass::aTest); // <-- How should I point to a's aClass::test function?
}
How can I use the a's aClass::test as an argument to function1? I would like to access a member of the class.
There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus
void (aClass::*)(int, int)
rather than the type you try to use
void (*)(int, int)
One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).
If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.
In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().
The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.
To clarify how to use a function pointer to call a member function, here is an example:
// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
fptr(context, 17, 42);
}
void non_member(void*, int i0, int i1) {
std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}
struct foo {
void member(int i0, int i1) {
std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
}
};
void forwarder(void* context, int i0, int i1) {
static_cast<foo*>(context)->member(i0, i1);
}
int main() {
somefunction(&non_member, nullptr);
foo object;
somefunction(&forwarder, &object);
}
#Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:
#include <functional>
using namespace std::placeholders;
void function1(std::function<void(int, int)> fun)
{
fun(1, 1);
}
int main (int argc, const char * argv[])
{
...
aClass a;
auto fp = std::bind(&aClass::test, a, _1, _2);
function1(fp);
return 0;
}
A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be
void function1(void (aClass::*function)(int, int), aClass& a) {
(a.*function)(1, 1);
}
and to call it:
aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);
Since 2011, if you can change function1, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
(live demo)
Notice also that I fixed your broken object definition (aClass a(); declares a function).
I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference
Important to note that unless you can change the signature of the code taking the function, there is no (easy) way to do this. That would be trying to implement a closure in a language that does not have closures that are the same as functions (the signature for a closure in C++ is different).
There are two actual ways to achieve this:
Use some sort of singleton/global variable that you store the closure in, and then pass a helper function that calls the needed function using that closure. Here is an example:
#include <stdio.h>
template<class C, typename ReturnType, typename... Args>
class ClosureSingleton {
typedef ReturnType (C::*FuncType)(Args...);
public:
static ClosureSingleton& getInstance() {
static ClosureSingleton instance;
return instance;
}
void setClosure(C* obj, FuncType f) {
this->obj = obj;
this->function = f;
}
static ReturnType funcPtr(Args... args) {
C* obj = getInstance().obj;
auto func = getInstance().function;
return (obj->*func)(args...);
}
private:
ClosureSingleton() {}
C* obj;
FuncType function;
public:
ClosureSingleton(ClosureSingleton const&) = delete;
void operator=(ClosureSingleton const&) = delete;
};
class aClass {
public:
void aTest1(int a, int b) { printf("%d + %d = %d\n", a, b, a + b); }
int aTest2(int a, int b) { return a + b; }
};
void function1(void (*function)(int, int)) {
function(1, 1);
}
int function2(int (*function)(int, int)) {
return function(1, 1);
}
int main() {
aClass tmp;
ClosureSingleton<aClass, void, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest1);
function1(&ClosureSingleton<aClass, void, int, int>::funcPtr);
ClosureSingleton<aClass, int, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest2);
printf(
"function2: %d\n",
function2(&ClosureSingleton<aClass, int, int, int>::funcPtr));
return 0;
}
Of course, this has the obvious downside that the closure needs to be set before every call, as well as some thread safety issues. Not ideal, but potentially workable in specific circumstances
Use something like asmjit or dynamic compilation to dynamically compile and pass the function in to the C code. This will only work on machines that allow heap section to be marked as executable. It is also very much non-portable as you will be writing assembly code to accomplish this. However, if you get it working, you will indeed have a true closure, albeit a substantially higher cost to creating the closure compared to how most programming languages implement closures (they do not duplicate the function assembly, instead they use a context object)
Patch the lib/dll that has the function handler to change it's signature to allow a context object. Again, a very brittle and non optimal solution.
My original answer, which does not really answer the question, but people found it useful:
Not sure why this incredibly simple solution has been passed up:
#include <stdio.h>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
template<class C>
void function1(void (C::*function)(int, int), C& c)
{
(c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(&test);
function1<aClass>(&aClass::aTest, a);
return 0;
}
Output:
1 - 1 = 0
1 + 1 = 2
I made the member function as static and all works:
#include <iostream>
class aClass
{
public:
static void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
void function1(int a,int b,void function(int, int))
{
function(a, b);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(10,12,test);
function1(10,12,a.aTest); // <-- How should I point to a's aClass::test function?
getchar();return 0;
}
If you actually don't need to use the instance a
(i.e. you can make it static like #mathengineer 's answer)
you can simply pass in a non-capture lambda. (which decay to function pointer)
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
int main()
{
//note: you don't need the `+`
function1(+[](int a,int b){return aClass{}.aTest(a,b);});
}
Wandbox
note: if aClass is costly to construct or has side effect, this may not be a good way.
You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.
http://cpp.sh/9jhk3
// Example program
#include <iostream>
#include <string>
using namespace std;
typedef int FooCooker_ (int);
// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
cout << "Cooking 10 Foo ..." << endl;
cout << "FooCooker:" << endl;
FooCooker (10);
}
struct Bar_ {
Bar_ (int Foo = 0) : Foo (Foo) {};
int cook (int Foo) {
cout << "This Bar got " << this->Foo << endl;
if (this->Foo >= Foo) {
this->Foo -= Foo;
cout << Foo << " cooked" << endl;
return Foo;
} else {
cout << "Can't cook " << Foo << endl;
return 0;
}
}
int Foo = 0;
};
// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* Bar1Ptr = NULL;
static int cook_in_Bar1 (int Foo) {
return Bar1Ptr->cook (Foo);
}
thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
return Bar2Ptr->cook (Foo);
}
int main () {
Bar1Ptr = new Bar_ (20);
cook_10_foo (cook_in_Bar1);
Bar2Ptr = new Bar_ (40);
cook_10_foo (cook_in_Bar2);
delete Bar1Ptr;
delete Bar2Ptr;
return 0;
}
Please comment on any issues with this approach.
Other answers fail to call existing plain C functions: http://cpp.sh/8exun

Call a C-style function address with std::bind and std::function.target using a method from object

I have a C-style function, which stores another function as an argument. I also have an object, which stores a method that must be passed to the aforementioned function. I built an example, to simulate the desired situation:
#include <functional>
#include <iostream>
void foo(void(*f)(int)) {
f(2);
}
class TestClass {
public:
std::function<void(int)> f;
void foo(int i) {
std::cout << i << "\n";
}
};
int main() {
TestClass t;
t.f = std::bind(&TestClass::foo, &t, std::placeholders::_1);
foo( t.f.target<void(int)>() );
return 0;
}
What is expected is that it will be shown on screen "2". But I'm having trouble compiling the code, getting the following message on the compiler:
error: const_cast to 'void *(*)(int)', which is not a reference, pointer-to-object, or pointer-to-data-member
return const_cast<_Functor*>(__func);
As I understand the use of "target", it should return a pointer in the format void () (int), related to the desired function through std :: bind. Why didn't the compiler understand it that way, and if it is not possible to use "target" to apply what I want, what would be the alternatives? I don't necessarily need to use std :: function, but I do need the method to be non-static.
This is a dirty little hack but should work
void foo(void(*f)(int)) {
f(2);
}
class TestClass {
public:
void foo(int i) {
std::cout << i << "\n";
}
};
static TestClass* global_variable_hack = nullptr;
void hacky_function(int x) {
global_variable_hack->foo(x);
}
int main() {
TestClass t;
global_variable_hack = &t;
foo(hacky_function);
return 0;
}
//can also be done with a lambda without the global stuff
int main() {
static TestClass t;
auto func = [](int x) {
t->foo(x); //does not need to be captured as it is static
};
foo(func); //non-capturing lambas are implicitly convertible to free functions
}

C++ Passing pointer to non-static member function

Hi everyone :) I have a problem with function pointers
My 'callback' function arguments are:
1) a function like this: int(*fx)(int,int)
2) an int variable: int a
3) another int: int b
Well, the problem is that the function I want to pass to 'callback' is a non-static function member :( and there are lots of problems
If someone smarter than me have some time to spent, he can look my code :)
#include <iostream>
using namespace std;
class A{
private:
int x;
public:
A(int elem){
x = elem;
}
static int add(int a, int b){
return a + b;
}
int sub(int a, int b){
return x - (a + b);
}
};
void callback( int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
int main()
{
A obj(5);
//PASSING A POINTER TO A STATIC MEMBER FUNCTION -- WORKS!!
// output = 'Value of the callback: 30'
callback(A::add, 10, 20);
//USING A POINTER TO A NON-STATIC MEMBER FUNCTION -- WORKS!!
int(A::*function1)(int, int) = &A::sub;
// output = 'Non static member: 3'
cout << "Non static member: " << (obj.*function1)(1, 1) << endl;
//PASSING A POINTER TO A NON-STATIC MEMBER FUNCTION -- aargh
// fallita! tutto quello sotto non funziona --> usa i funtori???
// puoi creare una classe wrapper ma non riuscirai mai a chiamare da callback
int(A::*function2)(int, int) = &A::sub;
int(*function3)(int, int) = obj.*function2; //[error] invalid use of non-static member function
callback(function3, 1, 1);
}
There's a way to create my pointer in the way I tried to wrote, like int(*fx)(int, int) = something? I searched a lot but no-one could gave me an answer (well, there was an answer: "NO", but I still think I can do something)
I heard also about functors, may them help me in this case?
Thanks to anyone
PS: sorry for my bad english
EDIT1:
I can use something like this:
template <class T>
void callback2( T* obj, int(T::*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << (obj->*fx)(a, b) << endl;
}
void callback2( void* nullpointer, int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
and in my main:
callback2(NULL, &mul, 5, 3); // generic function, it's like: int mul(int a, int b){return a*b;}
callback2(NULL, &A::add, 5, 3); //static member function
callback2(&obj, &A::sub, 1, 1); //non static member function
I'm not completely sadisfied, because I don't want to pass my 'callback2' the first parameter (the object)...
The question, for people that didn't understand my (bad) explanation, is: can I delete the first parameter in my callback2 function?
the prototype will be
void callback2(int(*fx)(int, int), int a, int b)<br>
and I will call like this:
callback2(&obj.sub, 1, 3);
Functions cannot be referenced this way:
int (*function3)(int, int) = obj.*function2;
You have to pass the address of the function like this:
int (*function3)(int, int) = std::mem_fn(&A::sub, obj);
// ^^^^^^^^^^^^^^^^^^^^^^^^^
The expression function2 decays into a pointer-to-function which allows it to work.
I would do it with std functors, here is a simple example based off of your code:
#include <iostream>
#include <functional>
using namespace std;
class A{
private:
int x;
public:
A(int elem){
x = elem;
}
static int add(int a, int b){
return a + b;
}
int sub(int a, int b) const{
return x - (a + b);
}
};
void callback( std::function<int(const A& ,int,int )> fx, A obj, int a, int b)
{
cout << "Value of the callback: " << fx( obj, a, b) << endl;
}
int main()
{
A obj(5);
std::function<int(const A& ,int,int )> Aprinter= &A::sub;
callback(Aprinter,obj,1,2);
}