C++調用全局函數與類成員函數


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*);

另外,對於類的虛函數,此方法不適用,因為在調用虛函數時,需要先確定類的虛函數表,在此我沒做過多分析

照目前這種情況對於我在寫線程類上,感覺是夠用了 ;)

具體格式看實際操作而定

如果我說的哪點不正確,請告知我 ;)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM