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();
}
Related
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);
}
};
//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.
I have some handle and I need to close it. There is some places in code, where handle may be closed. So, is this a right way to close handle?
HANDLE h;
....
if ( h != INVALID_HANDLE_VALUE ) {
::CloseHandle(h);
h = INVALID_HANDLE_VALUE;
}
There is a same question about bitmap handles:
HBITMAP hb;
....
if ( hb != INVALID_HANDLE_VALUE ) {
::DeleteObject(hb);
hb = INVALID_HANDLE_VALUE;
}
EDIT: I think, there is some misunderstanding. I know CloseHandle is for closing handles. I'd like to know proper way for closing handles. A similar situations occurs with deleting of pointers.
Foo *foo = new Foo();
// for example there is 2 functions that can delete foo
void bar() {
....
delete foo;
}
void duck() {
....
delete foo;
}
So, the following code means problems:
bar();
duck();
There is some workaround for this case. We need to define bar&duck functions like this:
void bar() {
....
if (foo) {
delete foo;
foo = NULL;
}
}
void duck() {
....
if (foo) {
delete foo;
foo = NULL;
}
}
So we avoid repeated deleting of foo. The question is What is the proper way to close handles? I mean, How to avoid repeated closing handles problem?
Not all functions that use HANDLE use CloseHandle(), some use other closing functions instead. Also, not all HANDLE values use INVALID_HANDLE_VALUE, either. Some use NULL instead.
HBITMAP never uses INVALID_HANDLE_VALUE, it always uses NULL. And you should never call DeleteObject() for an HBITMAP you do not own.
So the short answer is - if you are trying to create some general purpose handle management, don't bother. You are likely to get it wrong. If you allocate/open some handle, you have to know the correct way to close it, you can't guess at it.
If you want the handles to manage themselves, then RAII is the best choice. I prefer to use a templated class with specialized traits to reduce code duplication for differrent types of handles, eg:
template< class traits >
class HandleWrapper
{
private:
traits::HandleType FHandle;
public:
HandleWrapper()
FHandle(traits::InvalidValue)
{
}
HandleWrapper(const traits::HandleType value)
FHandle(value)
{
}
~HandleWrapper()
{
Close();
}
void Close()
{
if (FHandle != traits::InvalidValue)
{
traits::Close(FHandle);
FHandle = traits::InvalidValue;
}
}
bool operator !() const {
return (FHandle == traits:::InvalidValue);
}
operator bool() const {
return (FHandle != traits:::InvalidValue);
}
operator traits::HandleType() {
return FHandle;
}
};
.
struct KernelHandleTraits
{
typedef HANDLE HandleType;
static const HANDLE InvalidValue = INVALID_HANDLE_VALUE;
static void Close(HANDLE value)
{
CloseHandle(value);
}
};
HandleWrapper<KernelHandleTraits> hFile(CreateFile(...));
.
struct NullKernelHandleTraits
{
typedef HANDLE HandleType;
static const HANDLE InvalidValue = NULL;
static void Close(HANDLE value)
{
CloseHandle(value);
}
};
HandleWrapper<NullKernelHandleTraits> hMapping(CreateFileMapping(...));
.
struct FileMapViewTraits
{
typedef void* HandleType;
static const void* InvalidValue = NULL;
static void Close(void *value)
{
UnmapViewOfFile(value);
}
};
HandleWrapper<FileMapViewTraits> hView(MapViewOfFile(...));
.
struct GDIBitmapHandleTraits
{
typedef HBITMAP HandleType;
static const HBITMAP InvalidValue = NULL;
static void Close(HBITMAP value)
{
DeleteObject(value);
}
};
HandleWrapper<GDIBitmapTraits> hBmp(CreateBitmap(...));
Etc.
Use RAII pattern.
Wrap a handle into a class which allocates the handle in the constructor and destroys it in the destructor. You can find some examples in MFC, e.g. CGdiObject class for GDI objects like HBITMAP.
See also this SO question: RAII and smart pointers in C++
Yes.
CloseHandle() closes windows kernel object handles.
DeleteObject() deletes GDI objects.
I think your confusion comes from them both being called "handles", but they are different "classes" of objects. The term handle in HBITMAP is used here more as "opaque identifier". There is also plenty of documentation which assumes "handle" == "windows kernel handle".
In general if you're wondering how to delete something you should look at the constructor's documentation.
The following code is maybe what you're after:
BOOL CloseValidHandle(HANDLE& handle)
{
if (handle != INVALID_HANDLE_VALUE && handle != 0)
{
if (CloseHandle(handle))
{
handle = INVALID_HANDLE_VALUE;
return TRUE;
}
else
{
return FALSE;
}
}
return TRUE;
}
It's no RAII but it helps to delete/close handler.
class HandleDel : boost::notcopyable{
public:
HandleDel(HANDLE h, HANDLE invalid, BOOL(WINAPI *del)(HANDLE)):
h(h), invalid(invalid), del(del){
}
~HandleDel(){
if ( h != invalid ) del(h);
}
private:
HANDLE h;
HANDLE invalid;
BOOL(WINAPI *del)(HANDLE);
};
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.
*/
}
}
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.