How to get Windows thread pool to call class member function? - c++

I want the Windows thread pool (QueueUserWorkItem()) to call my class' member functions.
Unfortunately this cannot be done directly by passing a member function pointer as an argument to QueueUserWorkItem().
What makes it difficult is that more than one member function must be callable and they have different signatures (all return void though).
One probably need to add a few layers of abstraction to get this to work, but I'm not sure how to approach this. Any ideas?

This might help.
You can use tr1::function () and tr1::bind to "coalesce" various calls:
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace tr1;
class A
{
public:
void function(int i) { cout << "Called A::function with i=" << i << endl; }
};
void different_function(double c) {
cout << "Called different_function with c=" << c << endl;
}
int main(int argc, char* argv[])
{
function<void()> f = bind(different_function, 3.14165);
f();
A a;
f = bind(&A::function, a, 10);
f();
return 0;
}
The address of the function object can be passed as a single callable object (needing only one address).

Example:
In your class add:
char m_FuncToCall;
static DWORD __stdcall myclass::ThreadStartRoutine(LPVOID myclassref)
{
myclass* _val = (myclass*)myclassref;
switch(m_FuncToCall)
{
case 0:
_val->StartMyOperation();
break;
}
return 0;
}
Make a member for adding to queue then
void myclass::AddToQueue(char funcId)
{
m_FuncToCall=funcId;
QueueUserWorkItem(ThreadStartRoutine,this,WT_EXECUTEDEFAULT);
}
or create
typedef void (*MY_FUNC)(void);
typedef struct _ARGUMENT_TO_PASS
{
myclass* classref;
MY_FUNC func;
}ARGUMENT_TO_PASS;
and then
void myclass::AddToQueue(MY_FUNC func)
{
ARGUMENT_TO_PASS _arg;
_arg.func = func;
_arg.classref = this;
QueueUserWorkItem(ThreadStartRoutine,&_arg,WT_EXECUTEDEFAULT);
}
If you need further explanation feel free to ask :)
EDIT: You'll need to change the ThreadStartRoutine for the second example
and you can also change the struct to hold the passing argument

Related

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
}

How can I make a C++ member function by binding the arguments of another member function?

I am having problems with creating a variable of pointer-to-member-function (PTMF) type "on the fly" (that is, by pinning some arguments of an existing member function via std::bind). My question is if it is ever possible with C++11 or post-C++11 standard.
Preambula: I have a class that stores a static const array of std::functions initialized from PTMFs, hereinafter referred to as "handlers". Originally, they were regular member functions with a name and implementation so I didn't ever use C++11 and std::function. Then, I decided that many of them are nearly similar, and decided to generate them with a "generator function". I would like to avoid using templates for the generation because the number of these nearly similar handlers is going to dramatically increase in future (around 200+) and templatizing will just lead to code bloat.
If the PTMFs in question were static, I would have no problems with generating the handlers via std::bind. A simplified example:
#include <iostream>
#include <functional>
using namespace std;
struct A {
typedef function<void(int)> HandlerFn;
static void parametrized_handler(int i, const char *param) {
cout << "parametrized handler: " << param << endl;
}
static void handler(int i) { cout << "handler 1" << endl; }
int mm;
};
static const A::HandlerFn handler2 = [](int) { cout << "handler 2" << endl; };
static const A::HandlerFn handler3 = bind(A::parametrized_handler,
placeholders::_1,
"test_param");
int main()
{
A::handler(42);
handler2(42);
handler3(42);
return 0;
}
Output:
$ ./a.out
handler 1
handler 2
parametrized handler: test_param
The problem arises when I turn to non-static member functions. std::bind is not able to generate a function object that acts like a PTMF. I know that I can pass a real object as a first argument to bind and get a working function but that is not what I want: when I am initializing a static const array, there are no objects at all, and the result of bind will act as a regular non-member function anyway.
An expected implementation for non-static member functions (with an imaginary std::bind_mem binder):
#include <iostream>
#include <functional>
using namespace std;
struct A;
struct A {
typedef function<void(int)> HandlerFn;
void parametrized_handler(int i, const char *param) {
mm;
cout << "parametrized handler: " << param << endl;
}
void handler(int i) const { mm; cout << "handler 1" << endl; }
const HandlerFn handler2 = [this](int i) { mm; cout << "handler 2" << endl; };
int mm;
};
// An imaginary PTMF binder
// static const A::HandlerFn handler3 = bind_mem(A::parametrized_handler,
// placeholders::_1,
// "test_param");
int main()
{
A a;
(a.handler)(42);
(a.handler2)(42);
//(a.handler3)(42);
return 0;
}
Output:
$ ./a.out
handler 1
handler 2
So is there a way to implement a PTMF argument binding?
For binding a pointer to non static member function, you need an object.
#include<functional>
struct A {
typedef std::function<void(int)> HandlerFn;
void mem(int);
void static static_mem(int);
};
void foo() {
A a;
A::HandlerFn h1 = A::static_mem;
//This captures a by ref
A::HandlerFn h2 = std::bind(&A::mem, std::ref(a), std::placeholders::_1);
//This captures a by copy
A::HandlerFn h3 = std::bind(&A::mem, a, std::placeholders::_1);
//Change to =a for copy
A::HandlerFn h4 = [&a](int i){
a.mem(i);
};
h1(34);
h2(42);
}
Link:https://godbolt.org/g/Mddexq

Is there an analogue of an object's `this`, but for functions?

I have searched the reference and a general web, but I am unable to find out, if it exists.
Is there a way to get a pointer to the current function in C++? It is so trivial, that it should exist.
In the perfect world I would want to find a way to get an std::function of current function, but even an old style pointer would do.
To clarify why it may be needed: I am thinking about recursion inside a Lambda function or even general recursion in a function, with the high potential of the name change in the future releases.
There isn't, largely because there's no need for it. In the context of a (non-anonymous function) function, you always know where you stand - you can always use its name to refer to it or get its address. Unlike objects, where different ones have different addresses, ergo the need for this.
In general you can't. For example, in a lambda that's convertible to raw function pointer, there's no (standard language) way to obtain that pointer inside the function.
However, you can obtain the function name as a raw string, via the macro __func__, except that only the newest versions of the compilers provide it with that macro name.
Also, if you are OK with non-portable code there are several compiler-specific introspection facilities (I just know they exist, but would have to google them for you to list them).
Addressing the question's newly added part, how to let a function be recursive and still support easy name change and/or lambdas.
One way is to use a std::function, but much easier (and possibly a bit more efficient) is to just define the recursive function as an internal implementation detail, e.g. in a namespace or in an inner class:
#include <iostream>
using namespace std;
void foo( int const x )
{
struct Recursive {
inline static void foo( int const x )
{
cout << x << ' ';
if( x > 0 ) { foo( x - 1 ); }
}
};
Recursive::foo( x );
cout << endl;
}
auto main() -> int
{
foo( 3 );
}
How to do the above with a lambda instead of a named function:
#include <iostream>
using namespace std;
auto main() -> int
{
auto const foo = []( int const x ) -> void
{
struct Recursive {
inline static void foo( int const x )
{
cout << x << ' ';
if( x > 0 ) { foo( x - 1 ); }
}
};
Recursive::foo( x );
cout << endl;
};
foo( 3 );
}
If the purpose is just to obtain a std::function object, you might use the function name itself:
#include <iostream>
#include <functional>
using namespace std;
void functionA(int a);
void functionA(int a)
{
cout << "Thanks for calling me with " << a << endl;
if(a == 22)
return;
std::function<void(int)> f_display = functionA;
f_display(22);
}
int main() {
functionA(1);
return 0;
}
http://ideone.com/4C9gc5
but this isn't immune to name changing unfortunately. You might also encapsulate the function into something else to get rid of name changing:
#include <iostream>
#include <functional>
using namespace std;
void functionA(int a)
{
cout << "Thanks for calling me with " << a << endl;
}
template <typename F>
void encapsulateFunction(F f, int val)
{
std::function<void(int)> f_display = f;
// f_display now points to the function encapsulated
f_display(val);
}
int main() {
encapsulateFunction(functionA, 22);
return 0;
}
http://ideone.com/5Xb0ML
you can do this:
std::map<string, boost::any> functions;
int foo(int x) {
int (*fp)(int) = boost::any_cast<int (*)(int)>(functions[__func__]);
return x;
}
int main(int argc, char* argv[])
{
int (*fooPointer)(int) = foo;
boost::any fp = fooPointer;
functions["foo"] = fp;
...
}
insert a reference to the function into a global map and retrieve it from within the function. There's still room for encapsulating the map but I hope the idea is clear.
In c++ function is not a first class citizen so you will have to work a bit to get the function's reference.

C++ callback using class member

I know this has been asked so many times, and because of that it's difficult to dig through the cruft and find a simple example of what works.
I've got this, it's simple and it works for MyClass...
#include <iostream>
using std::cout;
using std::endl;
class MyClass
{
public:
MyClass();
static void Callback(MyClass* instance, int x);
private:
int private_x;
};
class EventHandler
{
public:
void addHandler(MyClass* owner)
{
cout << "Handler added..." << endl;
//Let's pretend an event just occured
owner->Callback(owner,1);
}
};
EventHandler* handler;
MyClass::MyClass()
{
private_x = 5;
handler->addHandler(this);
}
void MyClass::Callback(MyClass* instance, int x)
{
cout << x + instance->private_x << endl;
}
int main(int argc, char** argv)
{
handler = new EventHandler();
MyClass* myClass = new MyClass();
}
class YourClass
{
public:
YourClass();
static void Callback(YourClass* instance, int x);
};
How can that be rewritten so EventHandler::addHandler() will work with both MyClass and YourClass. I'm sorry but it's just the way my brain works, I need to see a simple example of what works before I can comprehend why/how it works. If you've got a favorite way to make this work now's the time to show it off, please markup that code and post it back.
[edit]
It was answered but the answer was deleted before I could give the checkmark.
The answer in my case was a templated function. Changed addHandler to this...
class EventHandler
{
public:
template<typename T>
void addHandler(T* owner)
{
cout << "Handler added..." << endl;
//Let's pretend an event just occured
owner->Callback(owner,1);
}
};
Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: std::function and std::bind:
#include <functional>
class EventHandler
{
public:
void addHandler(std::function<void(int)> callback)
{
cout << "Handler added..." << endl;
// Let's pretend an event just occured
callback(1);
}
};
The addHandler method now accepts a std::function argument, and this "function object" have no return value and takes an integer as argument.
To bind it to a specific function, you use std::bind:
class MyClass
{
public:
MyClass();
// Note: No longer marked `static`, and only takes the actual argument
void Callback(int x);
private:
int private_x;
};
MyClass::MyClass()
{
using namespace std::placeholders; // for `_1`
private_x = 5;
handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}
void MyClass::Callback(int x)
{
// No longer needs an explicit `instance` argument,
// as `this` is set up properly
cout << x + private_x << endl;
}
You need to use std::bind when adding the handler, as you explicitly needs to specify the otherwise implicit this pointer as an argument. If you have a free-standing function, you don't have to use std::bind:
void freeStandingCallback(int x)
{
// ...
}
int main()
{
// ...
handler->addHandler(freeStandingCallback);
}
Having the event handler use std::function objects, also makes it possible to use the new C++11 lambda functions:
handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });
Here's a concise version that works with class method callbacks and with regular function callbacks. In this example, to show how parameters are handled, the callback function takes two parameters: bool and int.
class Caller {
template<class T> void addCallback(T* const object, void(T::* const mf)(bool,int))
{
using namespace std::placeholders;
callbacks_.emplace_back(std::bind(mf, object, _1, _2));
}
void addCallback(void(* const fun)(bool,int))
{
callbacks_.emplace_back(fun);
}
void callCallbacks(bool firstval, int secondval)
{
for (const auto& cb : callbacks_)
cb(firstval, secondval);
}
private:
std::vector<std::function<void(bool,int)>> callbacks_;
}
class Callee {
void MyFunction(bool,int);
}
//then, somewhere in Callee, to add the callback, given a pointer to Caller `ptr`
ptr->addCallback(this, &Callee::MyFunction);
//or to add a call back to a regular function
ptr->addCallback(&MyRegularFunction);
This restricts the C++11-specific code to the addCallback method and private data in class Caller. To me, at least, this minimizes the chance of making mistakes when implementing it.
Note that with C++20's bind_front you can simplify add_callback for class member functions to:
template<class T> void addCallback(T* const object, void(T::* const mf)(bool,int))
{
callbacks_.emplace_back(std::bind_front(mf, object));
}
What you want to do is to make an interface which handles this code and all your classes implement the interface.
class IEventListener{
public:
void OnEvent(int x) = 0; // renamed Callback to OnEvent removed the instance, you can add it back if you want.
};
class MyClass :public IEventListener
{
...
void OnEvent(int x); //typically such a function is NOT static. This wont work if it is static.
};
class YourClass :public IEventListener
{
Note that for this to work the "Callback" function is non static which i believe is an improvement. If you want it to be static, you need to do it as JaredC suggests with templates.
A complete working example from the code above.... for C++11:
#include <stdlib.h>
#include <stdio.h>
#include <functional>
#if __cplusplus <= 199711L
#error This file needs at least a C++11 compliant compiler, try using:
#error $ g++ -std=c++11 ..
#endif
using namespace std;
class EventHandler {
public:
void addHandler(std::function<void(int)> callback) {
printf("\nHandler added...");
// Let's pretend an event just occured
callback(1);
}
};
class MyClass
{
public:
MyClass(int);
// Note: No longer marked `static`, and only takes the actual argument
void Callback(int x);
private:
EventHandler *pHandler;
int private_x;
};
MyClass::MyClass(int value) {
using namespace std::placeholders; // for `_1`
pHandler = new EventHandler();
private_x = value;
pHandler->addHandler(std::bind(&MyClass::Callback, this, _1));
}
void MyClass::Callback(int x) {
// No longer needs an explicit `instance` argument,
// as `this` is set up properly
printf("\nResult:%d\n\n", (x+private_x));
}
// Main method
int main(int argc, char const *argv[]) {
printf("\nCompiler:%ld\n", __cplusplus);
new MyClass(5);
return 0;
}
// where $1 is your .cpp file name... this is the command used:
// g++ -std=c++11 -Wall -o $1 $1.cpp
// chmod 700 $1
// ./$1
Output should be:
Compiler:201103
Handler added...
Result:6
MyClass and YourClass could both be derived from SomeonesClass which has an abstract (virtual) Callback method. Your addHandler would accept objects of type SomeonesClass and MyClass and YourClass can override Callback to provide their specific implementation of callback behavior.
If you have callbacks with different parameters you can use templates as follows:
// compile with: g++ -std=c++11 myTemplatedCPPcallbacks.cpp -o myTemplatedCPPcallbacksApp
#include <functional> // c++11
#include <iostream> // due to: cout
using std::cout;
using std::endl;
class MyClass
{
public:
MyClass();
static void Callback(MyClass* instance, int x);
private:
int private_x;
};
class OtherClass
{
public:
OtherClass();
static void Callback(OtherClass* instance, std::string str);
private:
std::string private_str;
};
class EventHandler
{
public:
template<typename T, class T2>
void addHandler(T* owner, T2 arg2)
{
cout << "\nHandler added..." << endl;
//Let's pretend an event just occured
owner->Callback(owner, arg2);
}
};
MyClass::MyClass()
{
EventHandler* handler;
private_x = 4;
handler->addHandler(this, private_x);
}
OtherClass::OtherClass()
{
EventHandler* handler;
private_str = "moh ";
handler->addHandler(this, private_str );
}
void MyClass::Callback(MyClass* instance, int x)
{
cout << " MyClass::Callback(MyClass* instance, int x) ==> "
<< 6 + x + instance->private_x << endl;
}
void OtherClass::Callback(OtherClass* instance, std::string private_str)
{
cout << " OtherClass::Callback(OtherClass* instance, std::string private_str) ==> "
<< " Hello " << instance->private_str << endl;
}
int main(int argc, char** argv)
{
EventHandler* handler;
handler = new EventHandler();
MyClass* myClass = new MyClass();
OtherClass* myOtherClass = new OtherClass();
}

C++ function with function parameter more elegant

I have the following code:
#include <iostream>
using namespace std;
class A
{
int m_value;
public:
A(int value)
{
m_value = value;
funcA(&A::param);
}
void funcA(void (A::*function)(int))
{
(this->*function)(m_value);
}
void param(int i)
{
cout << "i = " << i << endl;
}
};
int main()
{
A ob(10);
return 0;
}
I have a class in which I call a function that receives another function as parameter. The function call is at line funcA(&A::param). What I want is to be able to pass a function as parameter without being necessary to specify the class scope: funcA(&param). Also I didn't want to use typedefs that's why I have the code a little 'dirty'.
Is there any possibility to achieve this?
This cannot be done. A function pointer in a class must be identified using the class scope (A::function)
That is kind of ugly.
The first thing you should look at doing is recoding things to use inheritence and dynamic dispatch instead. To do this you change the A class to have a virtual method that funcA calls
class A {
...
void funcA () {
custom_function(m_value);
}
protected:
virtual void custom_function (int)=0;
}
Now for every different custom_function you want to use, you declare a new class derived from A, and implement the function in there. It will automagically get called from funcA:
class A_print : public A {
public:
virtual void custom_function (int param) {
std::cout << "param was " << param << std::endl;
}
}
If that isn't flexible enough for you, the next best C++-ish solution would be to implement a functor (an object that acts as a function, possibly even overriding the ()operator.
I don't understand why you can't just do this:
#include <iostream>
using namespace std;
class A
{
int m_value;
public:
A(int value)
{
param(value);
}
void param(int i)
{
cout << "i = " << i << endl;
}
};
int main()
{
A ob(10);
return 0;
}