0228 c c++ callback member funciton Singleton

最后还是这样,产生一个全局的单态类实例指针,然后再在静态函数里面倒腾吧

Program 77
#include <iostream>
#include <windows.h>
using namespace std;

typedef void(*pFUN)();

#pragma pack(push,1)
// structure to store the machine code
struct Thunk
&leftsign;
    BYTE    m_jmp;          // op code of jmp instruction
    DWORD   m_relproc;      // relative jmp
&rightsign;;
#pragma pack(pop)

class C
&leftsign;
public:
    Thunk    m_thunk;
    static  C* g_pC = NULL;

    static C *instance() &leftsign;
  if (g_pC == NULL)
   g_pC = new C();
  
  return g_pC;
 &rightsign;

    void Init(pFUN pFun, void* pThis)
    &leftsign;
        // op code of jump instruction
        m_thunk.m_jmp = 0xe9;
        // address of the appripriate function
        m_thunk.m_relproc = (int)pFun – ((int)this+sizeof(Thunk));

        FlushInstructionCache(GetCurrentProcess(),
                                &m_thunk, sizeof(m_thunk));
    &rightsign;

    // this is cour call back function
    static void CallBackFun()
    &leftsign;
        C* pC = g_pC;

        // initilize the thunk
        pC->Init(StaticFun, pC);

        // get the address of thunk code
        pFUN pFun = (pFUN)&(pC->m_thunk);

        // start executing thunk code which will call StaticFun
        pFun();

        cout << "C::CallBackFun" << endl;
    &rightsign;

    static void StaticFun()
    &leftsign;
        cout << "C::StaticFun" << endl;
    &rightsign;
&rightsign;;

int main()
&leftsign;
    C objC;
    g_pC = &objC;
    C::CallBackFun();
    return 0;
&rightsign;

The output of this program is

C::StaticFun
C::CallBackFun

Here StaticFun is called through the thunk, which is initialized in the Init member function. The execution of program is something like this

CallBackFun
Init (to initialize the thunk)
Get the address of thunk
Execute thunk
Thunk code call StaticFun

 0228 LINUX WINDOW C C++ 回调函数 成员函数 error (2006-6-23)

· 0228 C C++ callback  memberfunc info (2006-6-22)

· 0228 cdecl VC callback c2664 (2006-6-21)

· 0228 cdecl C2664 msdn (2006-6-20)

历史博文

标签:, , ,
六月 24, 2006 at 4:55 下午 by yippee 1,031 次
Category: Dev
Tags: , , ,