Re: Function Pointer Query
- From: Rich S. <RichS@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 23 Mar 2006 23:52:04 -0800
"Igor Tandetnik" wrote:
"Rich S." <RichS@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:CAAA1E12-6432-4B32-9053-8047799C13E0@xxxxxxxxxxxxx
Is it possible to have a function pointer that points to a function
in a class that is NON-static?
Here's a pointer to member function:
class C {
public:
void f(int);
};
typedef void (C::*PF)(int);
PF pf = &C::f;
C c;
(c.*pf)(1); // calls c.f(1)
Note that pointer to member function is incompatible with regular
function pointer. You can't pass the former where the latter is
expected. If you hope to pass a member function pointer to some API that
needs a callback, you are sadly out of luck. Most APIs taking a callback
require a non-member or a static member function.
Since static member functions are so inconvenient, I am hoping that
there is a way to pass a pointer to a function that is non-static.
Most APIs that take a callback also take a context (aka closure)
parameter that they pass right back to the callback. Let's take
EnumWindows:
class C {
public:
void EnumWindows();
BOOL EnumProc(HWND);
static BOOL CALLBACK EnumProcStatic(HWND, LPARAM);
};
void C::EnumWindows() {
::EnumWindows(EnumProcStatic, reinterpret_cast<LPARAM>(this));
}
BOOL CALLBACK C::EnumProcStatic(HWND hwnd, LPARAM lparam) {
C* pThis = reinterpret_cast<C*>(lparam);
return pThis->EnumProc(hwnd);
}
BOOL C::EnumProc(HWND hwnd) {
// Do actual work here
}
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925
Thank you Igor. I was vaguely aware of things called "pointer to member",
but I did not know how they fit into the scheme of things before your answer.
I guess I will have to implement one of the workarounds that you and Carl
mentioned.
Rich
.
- Follow-Ups:
- Re: Function Pointer Query
- From: Eugene Gershnik
- Re: Function Pointer Query
- References:
- Re: Function Pointer Query
- From: Igor Tandetnik
- Re: Function Pointer Query
- Prev by Date: How to get notification in my application when a document it opened is modified
- Next by Date: Re: Function Pointer Query
- Previous by thread: Re: Function Pointer Query
- Next by thread: Re: Function Pointer Query
- Index(es):
Relevant Pages
|