How to pass "this" pointer to a global function - c++

//This is AsynchronousFunction class header file
typedef int (*functionCall)(int, int);
DWORD __stdcall functionExecuter(LPVOID pContext); // global function
class AsynchronousFunction
{
int param1, param2;
functionCall fCall;
HANDLE m_handle;
public:
AsynchronousFunction(functionCall, int, int);
~AsynchronousFunction();
int result();
protected:
private:
int returnVal;
};
It's implementation as follows
AsynchronousFunction::AsynchronousFunction(functionCall fCall, int param1, int param2):m_handle(CreateEvent( NULL , false , false , NULL))
{
bool b = QueueUserWorkItem(functionExecuter, this, WT_EXECUTEDEFAULT);
WaitForSingleObject(m_handle, INFINITE);
SetEvent(m_handle);
}
AsynchronousFunction::~AsynchronousFunction()
{
CloseHandle(m_handle);
}
int AsynchronousFunction::result()
{
return 0;// not implemented yet
}
DWORD __stdcall functionExecuter(LPVOID pContext)
{
return 0;
}
here pContext receives "this" pointer. my attempt is access the param1 and param2
from here and do the work
how can I do this ?

Either you can make the functionExecuter a friend of AsynchronousFunction
OR
Add a public function in AsynchronousFunction which does the required things and call it from functionExecuter, something like shown below.
DWORD __stdcall functionExecuter(LPVOID pContext)
{
return (reinterpret_cast<AsyncrhonousFunction*>(pContext))->realFunctionExecuter();
}

#sajas Sorry, I don't have an explicit reference other than to refer to Scott Meyers' books or Herb Sutter books; it's just one of those things I picked up along the way. In general, you don't want to break encapsulation by exposing private data if it's not needed, which is exactly what friends do. In this case, if you decide to change the implementation of AsynchronousFunction tomorrow and functionExecuter was its friend, then it's more likely that you could break functionExecuter because it might have relied on the private members; on the other hand, if it was never a friend to begin with, you'd be forced to code functionExecuter using AsynchronousFunction's public interface only.

Related

Recasting const function

I'm using a library (libtcod) that has an A* pathfinding algorithm. My class inherits the callback base class, and I implement the required callback function. Here is my generic example:
class MyClass : public ITCODPathCallback
{
...
public: // The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() { // non-const stuff }
};
I found a number of examples using const_cast and static_cast, but they seemed to be going the other way, making a non-const function be able to return a const function result. How can I do it in this example?
getWalkCost() is defined by my library that I cannot change, but I want to be able to do non-const things in it.
The best solution depends on why you want to do non-const stuff. For example, if you have a cache of results that you want to use to improve performance, then you can make the cache be mutable, since that preserves the logical constness:
class MyClass : public ITCODPathCallback
{
...
public: // The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() const { // ok to modify cache here }
mutable std::map<int,int> cache;
};
Or perhaps you want to record some statistics about how many times the getWalkCost was called and what the maximum x value was, then passing a reference to the statistics may be best:
class MyClass : public ITCODPathCallback
{
...
public:
struct WalkStatistics {
int number_of_calls;
int max_x_value;
WalkStatistics() : number_of_calls(0), max_x_value(0) { }
};
MyClass(WalkStatistics &walk_statistics)
: walk_statistics(walk_statistics)
{
}
// The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() const { // ok to modify walk_statistics members here }
WalkStatistics &walk_statistics;
};
You can hack it this way:
return const_cast<MyClass*>(this)->doSomeMath();
Of course this won't be considered good design by most people, but hey. If you prefer you can instead make doSomeMath() const, and mark the data members it modifies as mutable.

FunktionPointerArray in Singleton

I try to implement an array of function pointers in an singleton owning a thread.
In the thread function I get an error, telling me that a member has to be relative to an object. More in the commentline...
Header:
typedef struct{
int action;
HWND handle;
}JOB;
class Class{
public:
enum Action { 1,2 };
private:
JOB m_currentJob;
queue<JOB> Jobs;
static DWORD WINAPI ThreadFunction(LPVOID lpParam);
void (Class::*ftnptr[2])(JOB Job);
void Class::ftn1(JOB Job);
void Class::ftn2(JOB Job);
// Singleton pattern
public:
static Class* getInstance(){
if(sInstance == NULL)
sInstance = new Class();
return sInstance;
}
private:
Class(void);
~Class(void);
static Class* sInstance;
};
Body:
#include "Class.h"
Class* Class::sInstance = NULL;
Class::Class(){
this->ftnptr[0] = &Class::ftn1;
this->ftnptr[1] = &Class::ftn2;
}
DWORD WINAPI Class::AutoplayerThreadFunction(LPVOID lpParam)
{
Class *pParent = static_cast<Class*>(lpParam);
while(true){
(pParent->*ftnptr[pParent->m_currentJob.action])(pParent->m_currentJob);
/* The line above causes the compiler error. Curious to me is that
* neither "pParent->m_currentJob" nor "pParent->m_currentJob" cause
* any problems, although they are members too like the ftnptr array.
*/
}
}
void Class::ftn1(JOB Job){}
void Class::ftn2(JOB Job){}
A call via getInstance from the SingletonPattern doesnt make it any better.
Any suggestions?
ftnptr is a member of Class. However, you access it directly. That is, pParent->*ftnptr[...] means "access the member of pParent designated by the pointer ftnptr[...]", but it doesn't imply that ftnptr too is a member of pParent.
The correct code is (pParent->*(pParent->ftnptr[...]))(...). But I would recommend extracting the array index expression from that:
auto fnptr = pParent->ftnptr[...];
(pParent->*fnptr)(...);
I think it might be how you declare your array of pointer-to-member-functions. (Edit: This wasn't what was wrong. I'm keeping this answer up anyway, because typedefs for function pointers can really make code cleaner, so I think this is good advice.)
Try using a typedef:
typedef void (Class::*ftnptr)(JOB Job);
ftnptr[2] fn_ptrs;
Then use it like so:
Class::Class(){
this->fn_ptrs[0] = &Class::ftn1;
this->fn_ptrs[1] = &Class::ftn2;
}
DWORD WINAPI Class::AutoplayerThreadFunction(LPVOID lpParam)
{
Class *pParent = static_cast<Class*>(lpParam);
while(true){
(pParent->*(pParent->fn_ptrs[pParent->m_currentJob.action]))(pParent->m_currentJob);
/* The line above causes the compiler error. Curious to me is that
* neither "pParent->m_currentJob" nor "pParent->m_currentJob" cause
* any problems, although they are members too like the ftnptr array.
*/
}
}

Member function pointer passing for callback use case

I use a 3rd party library, that does callback operations.
It has a function which takes in function pointers.
The problem is that I are unable to pass in pointers to functions that are members of a class.
I am using Qt and C++. The 3rd party library function seems to be a C function.
The example code provided by the third party puts all code in main.
This is undesirable, I need to wrap code in classes.
How can I solve this callback issue?
A.h
#include "ThirdPartyLibrary.h"
class A
{
public:
QFile* f;
A(QString filename);
~A();
bool mount();
BOOL _stdcall OnWriteCallback
(
DRIVE_HANDLE h,
ULONGLONG WriteOffset,
ULONG WriteSize,
const void* WriteBuffer,
ULONG *BytesWritten
);
BOOL _stdcall OnReadCallback
(
DRIVE_HANDLE h,
ULONGLONG ReadOffset,
ULONG ReadSize,
void* ReadBuffer,
ULONG *BytesRead
);
};
A.cpp
A::A(QString filename)
{
f = new QFile(filename);
f.open(QFile::ReadWrite);
}
~A::A(){
f.close();
delete f;
}
bool A::mount()
{
//THIS IS THE PROBLEM, CreateVirtualDrive does not take MEMBER FUNCTION POINTERS
//properly, instead it wants normal function pointers.
//CreateVirtualDrive is from an external 3rd-party
//library, and seems to be a C function.
g_hDrive = CreateVirtualDrive(driveLetter,DISK_SIZE,
&A::OnReadCallback,
&A::OnWriteCallback);
}
BOOL _stdcall A::OnWriteCallback
(
DRIVE_HANDLE h,
ULONGLONG WriteOffset,
ULONG WriteSize,
const void* WriteBuffer,
ULONG *BytesWritten
){
//do some work with QFile f !!
return true;
}
BOOL _stdcall A::OnReadCallback
(
DRIVE_HANDLE h,
ULONGLONG ReadOffset,
ULONG ReadSize,
void* ReadBuffer,
ULONG *BytesRead
){
//do some work with QFile f !!
return true;
}
main.cpp
#include "A.h"
int main ()
{
A a;
a.mount();
}
There's a workaround for this described in the C++ FAQ:
class Fred {
public:
void memberFn();
static void staticMemberFn(); // A static member function can usually handle it
...
};
// Wrapper function uses a global to remember the object:
Fred* object_which_will_handle_signal;
void Fred_memberFn_wrapper()
{
object_which_will_handle_signal->memberFn();
}
int main()
{
/* signal(SIGINT, Fred::memberFn); */ // Can NOT do this
signal(SIGINT, Fred_memberFn_wrapper); // OK
signal(SIGINT, Fred::staticMemberFn); // OK usually; see below
...
}
I am not experienced with QT, but most signalling/callback systems have different methods for the member functions than standard static function pointers.
For instance, in sigc++, they have
signal.connect(sigc::mem_fun(this, &Class::function));
I would think QT is similar.
If there is no such mechanism, you could, ugly but effective, have a static function which you pass as the callback, which then calls your member function.
Pointers to non-static member functions cannot be casted to free function pointers by C++ standard, as, in general, they are more complex structure than plain 'void *'.
In your case, it would be a good idea to establish global (serialized, if you have multithreading) one-to-one association between DRIVE_HANDLE and 'this' of an instance of class A and evaluate to that pointer in OnWriteCallback/OnReadCallback from the handle 'h' passed in.

Making a class friend itself

EDIT: It looks like I'm completely misinformed. Please close this thread. Gah.
For the record, the following compiles and works:
class ForeverAlone
{
private:
int m_friends;
HANDLE m_handle;
public:
ForeverAlone()
{
m_handle = CreateThread(NULL, 0, &ForeverAlone::SadThread, reinterpret_cast<void*>(this), 0, NULL);
}
~ForeverAlone()
{
if (m_handle != NULL)
CloseHandle(m_handle);
}
protected:
static unsigned long WINAPI SadThread(void* param)
{
ForeverAlone* thisObject = reinterpret_cast<ForeverAlone*>(param);
// is there any way for me to access:
thisObject->m_friends;
}
};
Original question: I have a static protected thread method, which I pass an object to. Can I somehow make the class friend itself so I can access its private members?
All class methods, static or not, are automatically "friends" of the class. Friend is used to allow external functions and classes access to a class. The class is always its own "friend".
Do this:
extern "c" DWORD __stdcall CInterfaceSadThread(LPVOID lpThreadParameter);
class ForeverAlone
{
private:
int m_friends;
HANDLE m_handle;
public:
ForeverAlone()
{
m_handle = CreateThread(NULL, 0,
&CInterfaceSadThread,
//
// You may get arguments about using static_cast here
// I still prefer reinterpret_cast as it makes it stick out
// Thus I check it more carefully when I see it.
// For this situation it works correctly
// As casting to void* and back to the original are guaranteed.
reinterpret_cast<void*>(this),
0, NULL);
}
~ForeverAlone()
{
if (m_handle != NULL)
CloseHandle(m_handle)
}
protected:
friend DWORD CInterfaceSadThread(LPVOID lpThreadParameter);
DWORD WINAPI SadThread()
{
// Do Stuff here
// Note: Just because you get here does not mean that the object is finished
// initializing. The parent thread may have been suspended after this
// one was created. Thus checking the state of member variables at this
// point is dangerous unless you can guarantee that construction has finished
return result;
}
};
Then in the callback just access your function;
extern "c" DWORD __stdcall CInterfaceSadThread(LPVOID lpThreadParameter)
{
// Note: You can only cast back to ForeverAlone* so be carefull
// Hence I use reinterpret_cast as this forces me to double check.
ForeverAlone* alone = reinterpret_cast<ForeverAlone*>(lpThreadParameter);
return alone->SadThread();
}

raw function pointer from a bound method

I need to bind a method into a function-callback, except this snippet is not legal as discussed in demote-boostfunction-to-a-plain-function-pointer.
What's the simplest way to get this behavior?
struct C {
void m(int x) {
(void) x;
_asm int 3;
}};
typedef void (*cb_t)(int);
int main() {
C c;
boost::function<void (int x)> cb = boost::bind(&C::m, &c, _1);
cb_t raw_cb = *cb.target<cb_t>(); //null dereference
raw_cb(1);
return 0;
}
You can make your own class to do the same thing as the boost bind function. All the class has to do is accept the function type and a pointer to the object that contains the function. For example, this is a void return and void param delegate:
template<typename owner>
class VoidDelegate : public IDelegate
{
public:
VoidDelegate(void (owner::*aFunc)(void), owner* aOwner)
{
mFunction = aFunc;
mOwner = aOwner;
}
~VoidDelegate(void)
{}
void Invoke(void)
{
if(mFunction != 0)
{
(mOwner->*mFunction)();
}
}
private:
void (owner::*mFunction)(void);
owner* mOwner;
};
Usage:
class C
{
void CallMe(void)
{
std::cout << "called";
}
};
int main(int aArgc, char** aArgv)
{
C c;
VoidDelegate<C> delegate(&C::CallMe, &c);
delegate.Invoke();
}
Now, since VoidDelegate<C> is a type, having a collection of these might not be practical, because what if the list was to contain functions of class B too? It couldn't.
This is where polymorphism comes into play. You can create an interface IDelegate, which has a function Invoke:
class IDelegate
{
virtual ~IDelegate(void) { }
virtual void Invoke(void) = 0;
}
If VoidDelegate<T> implements IDelegate you could have a collection of IDelegates and therefore have callbacks to methods in different class types.
Either you can shove that bound parameter into a global variable and create a static function that can pick up the value and call the function on it, or you're going to have to generate per-instance functions on the fly - this will involve some kind of on the fly code-gen to generate a stub function on the heap that has a static local variable set to the value you want, and then calls the function on it.
The first way is simple and easy to understand, but not at all thread-safe or reentrant. The second version is messy and difficult, but thread-safe and reentrant if done right.
Edit: I just found out that ATL uses the code generation technique to do exactly this - they generate thunks on the fly that set up the this pointer and other data and then jump to the call back function. Here's a CodeProject article that explains how that works and might give you an idea of how to do it yourself. Particularly look at the last sample (Program 77).
Note that since the article was written DEP has come into existance and you'll need to use VirtualAlloc with PAGE_EXECUTE_READWRITE to get a chunk of memory where you can allocate your thunks and execute them.
#include <iostream>
typedef void(*callback_t)(int);
template< typename Class, void (Class::*Method_Pointer)(void) >
void wrapper( int class_pointer )
{
Class * const self = (Class*)(void*)class_pointer;
(self->*Method_Pointer)();
}
class A
{
public:
int m_i;
void callback( )
{ std::cout << "callback: " << m_i << std::endl; }
};
int main()
{
A a = { 10 };
callback_t cb = &wrapper<A,&A::callback>;
cb( (int)(void*)&a);
}
i have it working right now by turning C into a singleton, factoring C::m into C::m_Impl, and declaring static C::m(int) which forwards to the singleton instance. talk about a hack.