Click here to Skip to main content
15,893,486 members
Articles / Desktop Programming / Win32

Generic Thunk with 5 combinations of Calling Conventions

Rate me:
Please Sign up or sign in to vote.
2.78/5 (8 votes)
13 Apr 2008CPOL12 min read 33.4K   398   19  
A simple and generic solution of making a member function become a callback function with the help of thunk technology.
#ifndef OWN_THUNK_CDECL_TO_CDECL_H_080327
#define OWN_THUNK_CDECL_TO_CDECL_H_080327

#include <Thunk/ThunkBase.h>

#define CDECL_TO_CDECL_CODES()				\
/*	CALL Hook	*/							\
CONST	CODE_FIRST(byte,CALL,0xE8)			\
CONST	CODE(dword,HOOK,0)					\
											\
/*	this and member function	*/			\
		CODE(dword,m_method,0)				\
		CODE(dword_ptr,m_this,0)			\
											\
/*	member function return here!	*/		\
/*	MOV ESP,oldESP	*/						\
CONST	CODE(byte,MOV_ESP,0xBC)				\
CONST	CODE(dword,oldESP,0)				\
											\
/*	JMP oldRet	*/							\
CONST	CODE(byte,JMP,0xE9)					\
CONST	CODE(dword,oldRet,0)				\
											\
/*	RET	*/									\
//CONST	CODE(byte,RET,0xC3)

namespace Thunk
{
	class CdeclToCdecl;
	typedef CdeclToCdecl StdToCdecl;

	class CdeclToCdecl
	{
	public:

		~CdeclToCdecl();
		explicit CdeclToCdecl(const void *Obj=0,int method=0);
		CdeclToCdecl(const CdeclToCdecl &src);
		CdeclToCdecl& operator = (const CdeclToCdecl &rhs);

		bool operator == (const CdeclToCdecl &rhs) const;
		bool operator != (const CdeclToCdecl &rhs) const;

		const void* Attach(const void *newObj);
		int Attach(int newMethod);

		template<typename Method>
		int AttachMethod(Method newMethod);

		template<typename Callback>
		Callback MakeCallback() const;

		template<typename Callback>
		operator Callback() const { return MakeCallback<Callback>(); }

	private:

		static void Hook();

		dword_ptr GetObject() const;
		void SetObject(dword_ptr newObj);

		dword GetMethod() const;
		void SetMethod(dword newMethod);

#pragma pack( push , 1)
		CDECL_TO_CDECL_CODES()
#pragma pack( pop )

	};

	template<typename Method>
	int CdeclToCdecl::AttachMethod(Method newMethod)
	{
		return Attach( Helper::PointerToInt32(newMethod) );
	}

#pragma warning( push )
#pragma warning( disable : 4311 )
	template<typename Callback>
	Callback CdeclToCdecl::MakeCallback() const
	{
		return reinterpret_cast<Callback>( this );
	}
#pragma warning( pop )

}

#endif	//#ifndef OWN_THUNK_CDECL_TO_CDECL_H_080327

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions