Click here to Skip to main content
15,885,954 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_BASE_H_080325
#define OWN_THUNK_BASE_H_080325

#include <stdint.h>
//#include <boost/static_assert.hpp>

#include <Thunk/MachineCodeMacro.h>

namespace Thunk
{
	typedef uint8_t		byte;
	typedef uint16_t	word;
	typedef int32_t		dword;
	typedef const void*	dword_ptr;

	//BOOST_STATIC_ASSERT(sizeof(byte)==1);
	//BOOST_STATIC_ASSERT(sizeof(word)==2);
	//BOOST_STATIC_ASSERT(sizeof(dword)==4);
	//BOOST_STATIC_ASSERT(sizeof(dword_ptr)==4);

#pragma pack ( push , 1)
	typedef struct int48
	{
		dword	address;
		word	selector;
	} int48;
#pragma pack ( pop )

	class Helper
	{
		friend class ThisToStd;
		friend class ThisToCdecl;
		friend class StdToStd;
		friend class CdeclToCdecl;

	public:
		template<typename Pointer>
		static int PointerToInt32(Pointer pointer);

	private:
		template<typename dst_type,typename src_type>
		static dst_type pointer_cast(src_type src);

		template<typename dst_type,typename src_type>
		static dst_type union_cast(src_type src);

		static void SetTransferDST(dword_ptr src,dword dst);
		static dword GetTransferDST(dword_ptr src);

		static void FlushInstructionCache(const void*Instructions,unsigned long size);
	};
	
	template<typename Pointer>
	int Helper::PointerToInt32(Pointer pointer)
	{
		return pointer_cast<int>(pointer);
	}

	template<typename dst_type,typename src_type>
	dst_type Helper::pointer_cast(src_type src)
	{
		return *static_cast<dst_type*>( static_cast<void*>(&src) );
	}

	template<typename dst_type,typename src_type>
	dst_type Helper::union_cast(src_type src)
	{
		union {
			src_type src;
			dst_type dst;
		} u = {src};
		return u.dst;
	}

}

#endif	//#ifndef OWN_THUNK_BASE_H_080325

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