Click here to Skip to main content
15,896,335 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_STDCALL_TO_STDCALL_H_080327
#define OWN_THUNK_STDCALL_TO_STDCALL_H_080327

#include <Thunk/ThunkBase.h>

#define STD_TO_STD_CODES()				\
/*	POP EAX	*/							\
CONST	CODE_FIRST(byte,POP_EAX,0x58)	\
/*	PUSH m_this	*/						\
CONST	CODE(byte,PUSH,0x68)			\
		CODE(dword_ptr,m_this,0)		\
/*	PUSH EAX	*/						\
CONST	CODE(byte,PUSH_EAX,0x50)		\
/*	JMP m_method(offset)	*/			\
CONST	CODE(byte,JMP,0xE9)				\
CONST	CODE(dword,m_method,0)

namespace Thunk
{
	class StdToStd
	{
	public:

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

		bool operator == (const StdToStd &rhs) const;
		bool operator != (const StdToStd &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:

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

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

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

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

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

}

#endif	//#ifndef OWN_THUNK_STDCALL_TO_STDCALL_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