Member function pointer passing for callback use case - c++

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.

Related

Pass non-static member function as a callback

I found several similar questions, but the solutions didn't suit my case.
In a C++ method, I call a C api, which takes a callback as one of its parameter.
class A
{
herr_t methodA(some parameters) {....}
void methodB(some parameters)
{
....
int status = CAPI(other parameters, callback, last parameter);
}
};
The prototype of CAPI is
herr_t CAPI( some parameters, H5L_iterate_t op, other parameters);
H5L_iterate_t is defined by
herr_t (*H5L_iterate_t)( hid_t g_id, const char *name,
const H5L_info_t *info, void *op_data)
methodA has the same signature as H5L_iterate_t.
In methodB,
status = CAPI(..., **(H5L_iterate_t )std::bind(&A::methodA, this,
std::placeholders::_1)**, ...);
The compile error I got was "Can't convert from ... to H5L_iterate_t". I'm wondering what's the right way to pass the non static member function as a callback.
Thanks in advance.
C APIs offering a callback almost always follow this pattern:
extern "C"
{
typedef void(*callback_function)(void* data);
typedef int handle_type;
void do_something_with_callback(handle_type, callback_function, void *data);
}
The idea being that whatever you pass as the data argument when do_something_with_callback is called, will be passed to the callback_function.
You can use this user data to pass a pointer to your c++ object's address, which you can then cast back to a pointer to your object type:
struct my_object
{
void initiate()
{
// call the C interface, passing our c-style callback function with
// a pointer to this class as the user data
do_something_with_callback(handle_, &callback_launch_function, this);
}
private:
static void callback_launch_function(void * data) {
// the data will always be a pointer to my_object -
// because that's what we passed.
auto self = reinterpret_cast<my_object*>(data);
self->handle_it();
}
// this is our c++style callback
void handle_it()
{
}
handle_type handle_;
};

C++ member function as callback function to external library

So below is a basic idea of what I'm trying to do.
I have an external library that I would like to use in an existing project.
I cannot change anything in the external library or the main function in the existing project of course.
The problem I face is how to pass a callback function I make in my class to this external function as a pointer to function. At the same time, this callback function has to have access to members of the class so I cannot simply make it static. How can I do it?
Class ExternalClass //This I cannot mess with.
{
//somestuff
void ExternalFunc (void(* callback)(int, const void*), const void *);
}
Class MyClass
{
//somestuff
ExternalClass m_ExObj;
void Callback(int x, const void *p){
//dosomething
//How do I use this pointer ?
}
void MyFunc(){
m_ExObj.ExternalFunc(/*Some way to put MyClass::Callback() in here*/)
}
}
The callback you have shown does not allow a user-defined value to be passed to it (otherwise you could use that for passing around your object pointer). It expects a standalone non-class function, so you have two options:
1) if the callback only ever calls into a single object at one time, then you can store the object pointer in a global or static variable, and then use a standalone function (or static class method) as the callback and have it use the global/static pointer to call your class method:
class MyClass
{
//somestuff
ExternalClass m_ExObj;
void Callback(int x)
{
//dosomething
}
static MyClass* objForCallback;
static void exObjCallback(int x) { objForCallback->Callback(x); }
void MyFunc()
{
objForCallback = this;
m_ExObj.ExternalFunc(&exObjCallback);
}
};
2) if you need to have callbacks for multiple objects at a time, you will have to wrap your class method inside a per-object thunk, where each thunk knows which object to call into, and then you use the thunks as callbacks. This is a more advanced technique, requiring an understanding of x86/x64 assembly and calling conventions, as you have to allocate memory dynamically and populate it with assembly instructions for each thunk to execute at runtime. For example, at least on Windows 32bit:
#pragma pack(push, 1)
struct MyThunk
{
unsigned char PopEAX_1; // POP the caller's return address off the stack
unsigned char PushThis; // PUSH the object 'this' pointer on to the stack
void *ThisValue;
unsigned char PushEAX_1; // PUSH the caller's return address back on to the stack
unsigned char Call; // CALL the callback function
__int32 CallAddr;
unsigned char PopEAX_2; // POP the caller's return address off the stack
unsigned char AddESP[3]; // Remove the object 'this' pointer from the stack
unsigned char PushEAX_2; // PUSH the caller's return address back on to the stack
unsigned char Return; // return to the caller
};
#pragma pack(pop)
typedef void (*CallbackType)(int);
class MyClass
{
CallbackType exObjCallback;
MyClass()
{
MyThunk *thunk = (MyThunk*) VirtualAlloc(NULL, sizeof(MyThunk), MEM_COMMIT, PAGE_READWRITE);
if (thunk)
{
thunk->PopEAX_1 = 0x58;
thunk->PushThis = 0x68;
thunk->ThisValue = this;
thunk->PushEAX_1 = 0x50;
thunk->Call = 0xE8;
thunk->CallAddr = reinterpret_cast<__int32>(Callback) - (reinterpret_cast<__int32>(&thunk->Call) + 5);
thunk->PopEAX_2 = 0x58;
thunk->AddESP[0] = 0x83;
thunk->AddESP[1] = 0xC4;
thunk->AddESP[2] = 0x04;
thunk->PushEAX_2 = 0x50;
thunk->Return = 0xC3;
DWORD dwOldProtect;
VirtualProtect(thunk, sizeof(MyThunk), PAGE_EXECUTE, &dwOldProtect);
FlushInstructionCache(GetCurrentProcess(), thunk, sizeof(MyThunk));
exObjCallback = (CallbackType) thunk;
}
}
~MyClass()
{
if (exObjCallback)
VirtualFree(exObjCallback, 0, MEM_RELEASE);
}
//somestuff
ExternalClass m_ExObj;
// NOTE: pCtx is the return address inside of ExternalFunc()
// where the callback is being called from. Because the
// callback is using the __cdecl calling convention, the
// thunk needs to remember this value and restore it after
// Callback() exits. Passing it as a parameter to Callback()
// is a quick-n-dirty way for the thunk to do that...
static void __cdecl Callback(void *pCtx, MyClass *pThis, int x)
{
//dosomething with pThis
}
void MyFunc()
{
if (exObjCallback)
m_ExObj.ExternalFunc(exObjCallback, ...);
}
};
When ExternalFunc() calls its callback, it will be calling the thunk, executing the instructions it contains. The thunk above is injecting the object's this pointer into the call stack as a parameter for Callback() as if ExternalFunc() had called it directly.
Update: in lieu of new information about the callback actually accepting a user-defined value, that greatly simplifies things:
class MyClass
{
//somestuff
ExternalClass m_ExObj;
static void Callback(int x, const void *p) {
MyClass *pThis = (MyClass*) p;
//dosomething with pThis
}
void MyFunc() {
m_ExObj.ExternalFunc(&Callback, this);
}
};

How to pass "this" pointer to a global function

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

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

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();
}