#include <iostream>
#include <windows.h>
using namespace std;
class C;
C* g_pC = NULL;
typedef void(*pFUN)();
#pragma pack(push,1)
// structure to store the machine code
struct Thunk
{
BYTE m_jmp; // op code of jmp instruction
DWORD m_relproc; // relative jmp
};
#pragma pack(pop)
class C
{
public:
Thunk m_thunk;
void Init(pFUN pFun, void* pThis)
{
// 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));
}
// this is cour call back function
static void CallBackFun()
{
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;
}
static void StaticFun()
{
cout << "C::StaticFun" << endl;
}
};
int main()
{
C objC;
g_pC = &objC;
C::CallBackFun();
return 0;
}
执行结果:
C::StaticFun
C::CallBackFun
代码还有疑问留着以后慢慢解读!