Leo

<2019年6月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

统计

  • 随笔 - 2
  • 文章 - 0
  • 评论 - 2
  • 引用 - 0

常用链接

留言簿(1)

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

2007年5月16日

如何让API回调你的VC类成员函数而不是静态函数

 

只要在函数声明前加static就好了,哈哈哈哈哈~~~~~  

。。。开个玩笑。以前确实大家都是这样做的,在静态的成员函数中再查找this指针,它多半是全局变量,或者是回调函数提供的附加参数。如果是前者,就会大大破坏程序的结构。而现在,随着社会生产力的发展,偶们已经能做到将成员函数映射成为一个临时的静态函数了。本文就来演示一下这种实现方式。

首先需要包含一个由yzwykkldczsh同志编写的模板类-----万能多用自适应无限制回调模板(为纪念友人fishskin,此模板又称为H>W模板) 

/**************************************************************************
 *   ACCallback.h
 *   Helper class of Member function callback mechanism
 **************************************************************************/
#include "stdafx.h"
#include "windows.h"

#pragma pack(push, 1)
struct _ACCallbackOpCodes
{
 unsigned char tag;  // CALL e8
 LONG_PTR offset;  // offset (dest - src - 5, 5=sizeof(tag + offset))
 LONG_PTR _this;   // a this pointer
 LONG_PTR _func;   // pointer to real member function address
};
#pragma pack(pop)

static __declspec( naked ) int STDACJMPProc()
{
 _asm
 {
  POP ECX 
  MOV EAX, DWORD PTR [ECX + 4] // func
  MOV ECX, [ECX]     // this  
  JMP EAX
 }
}

static LONG_PTR CalcJmpOffset(LONG_PTR Src, LONG_PTR Dest)
{
 return Dest - (Src + 5);
}

/*
 * NOTE: _TPStdFunc: a type of function pointer to API or Callbacks, *MUST* be _stdcall
         _TPMemberFunc: a type of function pointer to class member function,
         *MUST* be the *DEFAULT* calling conversation, *NO* prefix should be added,
          that is, using ECX for "this" pointer, pushing parameters from right to left,
          and the callee cleans the stack.
          _TClass: the class who owns the callback function. The caller should only own the _stdcall function pointer
   LIFE TIME:  It is important to keep the ACCallback object alive until the CALLBACK is not required!!!
 */
template<typename _TPStdFunc, class _TClass, typename _TPMemberFunc>
class ACCallback
{
public:
 _TClass *m_pThis;
 _TPMemberFunc m_pFunc;

private:
 _TPStdFunc m_pStdFunc;

 void MakeCode()
 {
  if (m_pStdFunc) ::VirtualFree(m_pStdFunc, 0, MEM_RELEASE);
  m_pStdFunc = (_TPStdFunc)::VirtualAlloc(NULL, sizeof(_ACCallbackOpCodes), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  _ACCallbackOpCodes *p = (_ACCallbackOpCodes *)m_pStdFunc;
  p->_func = *(LONG_PTR *)&m_pFunc;
  p->_this = (LONG_PTR)m_pThis;
  p->tag = 0xE8;
  p->offset = CalcJmpOffset((LONG_PTR)p, (LONG_PTR)STDACJMPProc);
 }

public:
 ACCallback<_TPStdFunc, _TClass, _TPMemberFunc>()
 {
 }
 ACCallback<_TPStdFunc, _TClass, _TPMemberFunc>(_TClass* pThis,
  _TPMemberFunc pFunc
  )
 {
  m_pFunc = pFunc;
  m_pThis = pThis;
  m_pStdFunc = NULL;
  MakeCode();
 }
 void Assign(_TClass* pThis,
  _TPMemberFunc pFunc
  )
 {
  m_pFunc = pFunc;
  m_pThis = pThis;
  m_pStdFunc = NULL;
  MakeCode();
 }
 ~ACCallback<_TPStdFunc, _TClass, _TPMemberFunc>()
 {
  ::VirtualFree(m_pStdFunc, 0, MEM_RELEASE);
 }
 operator _TPStdFunc()
 {
  return m_pStdFunc;
 }
};

/********************************** EXAMPLE **********************************
class CClass1
{
public:
 TCHAR m_Buf[255];
 BOOL EnumWindowProc(HWND hwnd, LPARAM lp)
 {
  GetWindowText(hwnd, m_Buf, 255);
  printf("Enum window=%s\n", m_Buf);
  return TRUE;
 }
 typedef BOOL (CClass1::*CLASSWNDENUMPROC)(HWND, LPARAM);
};

TO USE:
 CClass1 c1;
 ACCallback<WNDENUMPROC, CClass1, CClass1::CLASSWNDENUMPROC> cb(&c1, &CClass1::EnumWindowProc);
 EnumWindows(cb, 0);

************************* END OF EXAMPLE *********************************/

模板的三个参数分别是:API函数指针的类型,类名字,类成员函数指针的类型(两种函数指针在参数和返回值上应该一样,只是前者声明为_stdcall,后者不加任何调用修饰,即默认的__thiscall方式)
该项头文件的注释中给了一个调用API函数EnumWindows的例子。现在偶们来试试调用SetTimer。

class CTestCallback
{
private:
 /* A callback of SetTimer, mirrored into member OnTimer */
 typedef void (CTestCallback::*CLASSTIMERPROC)(HWND, UINT, UINT_PTR, DWORD);
 void OnTimer (HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
 ACCallback<TIMERPROC, CTestCallback, CLASSTIMERPROC> m_DOnTimer;
}

调用时,只要这样写:
/* 初始化回调结构 */
m_DOnTimer.Assign(this, &CTestCallback::OnTimer);
m_uid = ::SetTimer( NULL, 0, 1000, m_DOnTimer);

最后记得在CTestCallback的析构函数中KillTimer。由于m_DOnTimer会实现转化到静态函数指针类型的操作符,所以调用的地方只要直接写回调结构的名字就可以了。

使用该模板需要注意两点:
1.API函数应当是_stdcall类型的(这一点绝大部分API都满足)。类成员函数必须是默认的调用方式,不要加_stdcall或_cdecl之类的修饰。此方式的重要条件就在于_stdcall和__thiscall之间只相差了一个ECX指出的this指针,所以我们才能实现这种映射(这种方式在VCL和ATL的窗口类中都有使用到);
2.回调结构的生存周期应当是在整个回调函数有效的时间内。因此,对于EnumWindows这样的函数,只要声明在栈上就可以了;但对于SetTimer,就必须定义为类成员变量,同时,在类的析构函数中必须及时销毁这个timer。

posted @ 2007-05-16 13:32 LeoChen 阅读(1452) | 评论 (2)编辑 收藏
How to use SetTimer() with callback to a non-static member function

Quick update...

After reviewing the comments and suggestions from a few people, I made the solution better. Look for an update to this article which uses a better approach, namely using the functions:

  • CreateWaitableTimer()
  • SetWaitableTimer()
  • WaitForMultipleObjects()

The solution based on these functions will allow multiple instances of the CSleeperThread class to run (instead of just one using the current example). So stay tuned, I'll have this article updated as soon as possible. :-)

Introduction

I have seen many questions on the boards about how to properly use SetTimer(). I've also noticed that most of these questions are around how to put a thread to sleep for X seconds. One obvious answer would be to use the Sleep() function. The main drawback is, how do you gracefully shut down your thread, or cancel the Sleep() operation before the time expires.

This article is meant to address all of the above. I give an example of putting a thread to sleep using SetTimer(). The SetTimer() calls back to a non-static function. This is key, because normally you have to pass a static member to SetTimer() which means it can't access any other non-static variables or member functions of the class.

Details

Since implementing a non-static callback member is key to this, we'll go into this first. Implementing a callback to a static member function doesn't require anything different from implementing a regular C callback function. Since static member functions have the same signature as C functions with the same calling conventions, they can be referenced using just the function name.

Making a non-static callback member function is a different story, because they have a different signature than a C function. To make a non-static member function, it requires the use of two additional items:

  • A global (void*) pointer, referencing the class of the callback function
  • A wrapper function which will be passed to SetTimer()

This is actually a fairly simple implementation. First, you need to define your class:

class CSleeperThread : public CWinThread {
public:
static VOID CALLBACK TimerProc_Wrapper( HWND hwnd, UINT uMsg,
UINT idEvent, DWORD dwTime );
VOID CALLBACK TimerProc( HWND hwnd,
UINT uMsg, UINT idEvent, DWORD dwTime );
void ThreadMain();
void WakeUp();
private:
static void * pObject;
UINT_PTR pTimer;
CRITICAL_SECTION lock;
};

Then, don't forget to include the following line in your class implementation file:

void * CSleeperThread::pObject;

Now that we have our class declared, we can look at the wrapper function, the non-static member function and the member function that will call SetTimer():

VOID CALLBACK CSleeperThread::TimerProc_Wrapper( HWND hwnd, UINT uMsg,
UINT idEvent, DWORD dwTime ) {
CSleeperThread *pSomeClass = (CSleeperThread*)pObject; // cast the void pointer
pSomeClass->TimerProc(hwnd, uMsg, idEvent, dwTime); // call non-static function
}

The wrapper function first initializes a CSleeperThread pointer with pObject. Since pSomeClass is a local pointer, we can access it within the static wrapper function.

VOID CALLBACK CSleeperThread::TimerProc(HWND hwnd,
UINT uMsg, UINT idEvent, DWORD dwTime) {
::EnterCriticalSection(&lock);
if(idEvent == pTimer) {
KillTimer(NULL, pTimer);  // kill the timer so it won't fire again
ResumeThread();  // resume the main thread function
}
::LeaveCriticalSection(&lock);
}

The TimerProc member function isn't static, so we can access other non-static functions like ResumeThread() and we can access the private variable lock. Notice that I've entered a critical section which prevents a second timer event to enter the callback, thus ensuring that the first execution of TimerProc() will cancel out the timer.

Next, let's take a look at the main execution function, ThreadMain().

void CSleeperThread::ThreadMain()
{
pObject = this; // VERY IMPORTANT, must be initialized before
// calling SetTimer()
// call SetTimer, passing the wrapper function as the callback
pTimer = SetTimer(NULL, NULL, 10000, TimerProc_Wrapper);
// suspend until the timer expires
SuspendThread();
// the timer has expired, continue processing 
}

The first step in ThreadMain() is absolutely critical. We need to assign the class instance pointer (this) to the pObject variable. This is how the wrapper callback function will gain access to execute the non-static member function.

Next, we just call SetTimer() passing in a function pointer to our wrapper function. SetTimer() will call the wrapper function when the timer expires. The wrapper function in turn, will execute the non-static function TimerProc(), by accessing the static variable pSomeClass.

NOTE: I chose to implement a main function that will create the timer, go to sleep, continue processing and then exit when finished. This is in effect a function that will only execute once per timer. You could easily add a loop to ThreadMain() which would execute once for each timer event.

One last little function. Since we used SuspendThread() in ThreadMain(), if we need to wake up the thread (for whatever reason), all we have to do is make a call to ResumeThread(). So, I've added an access function like so:

void WakeUp() {
::EnterCriticalSection(&lock);
KillTimer(NULL, pTimer);
ResumeThread(); // wake the thread up
}

Buh dee buh dee, that's all folks...

And there we have it. A thread safe class that goes to sleep using SetTimer() and a non-static callback function; which also has the ability to wake up before the timer expires.

Hopefully, you have found this helpful. I've actually used this code in a project I'm working on now, and was in hopes someone else would get some good use out of it.

Someone once told me "you'll like programming if you like banging your head against the wall repeatedly". I've found that to be true, it took me literally several days to figure out what I've put into this article, I'm just slow I guess.

Whew, my head hurts, time for some Advil...or Ibooprofin.. or asssprin.... or something.

Credits...

I probably learned way more in the process of writing this article. So, much thanks goes to Lars Haendel for creating a web-site dedicated to understanding function pointers, without which I wouldn't know didley.

www.function-pointer.org.

posted @ 2007-05-16 10:31 LeoChen 阅读(1449) | 评论 (0)编辑 收藏
仅列出标题