您的位置:首页 > 编程语言 > C语言/C++

C++调用全局函数与类成员函数

2015-01-18 16:05 323 查看
void testfunc(void *param)
{
printf("\n\tcall global function %s\n", param);
}

void *GetClassFuncAddr(...)
{
DWORD address;

__asm
{
lea eax,address
mov edx, [ebp + 8]
mov [eax], edx
}

return (void *)address;
}

void *callfunc(void *pfn, void *pthis, void *param)
{
if (pthis != NULL)
{
unsigned long dwThis = (unsigned long)pthis;

typedef void* (__fastcall *memfunc)(void *,int, void*);//__fastcall调用方式会先传递两个DWORD参数(ecx与edx)
//typedef void* (__thiscall *memfunc)(void *, void*);//__thiscall调用方式传递ecx

/*typedef void* (__stdcall *memfunc)(void *);//__stdcall调用方式,此方式得准备this指针
__asm mov ecx, dwThis;
*/
return reinterpret_cast<memfunc>(pfn)(pthis, 0, param);
}
else
{
typedef void *(*normalfunc)(void*);
return reinterpret_cast<normalfunc>(pfn)(param);
}
}

class CTest
{
public:
void SimpleFunc(char *str)
{
printf("\n\tcall member function %s\n", str);
}

void SimpleCall(char *p)
{
callfunc(GetClassFuncAddr(&CTest::SimpleFunc), this, (void*)p);
}
};

int _tmain(int argc, _TCHAR* argv[])
{
CTest *pthis = new CTest();
char *str = "test str";

void *addr = GetClassFuncAddr(&CTest::SimpleCall);
callfunc(addr, pthis, (void*)str);

callfunc(&testfunc, NULL, (void*)str);
return 0;
}


补充一点的:以上都是建立在被呼叫函数的格式为

void *func(void*);

另外,对于类的虚函数,此方法不适用,因为在调用虚函数时,需要先确定类的虚函数表,在此我没做过多分析

照目前这种情况对于我在写线程类上,感觉是够用了 ;)

具体格式看实际操作而定

如果我说的哪点不正确,请告知我 ;)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: