Class designed to store and invoke function pointers and method pointers
Diff: GenericFunctionHandler.h
- Revision:
- 0:2aa4daee328e
- Child:
- 1:2418b141f599
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/GenericFunctionHandler.h Wed Nov 23 00:23:53 2011 +0000 @@ -0,0 +1,70 @@ +//mbed Microcontroller Library +//Class designed to store and invoke function pointers and method pointers +//Copyright 2011 +//Thomas Hamilton + +#ifndef GenericFunctionHandlerLibrary +#define GenericFunctionHandlerLibrary + +class GenericFunctionHandler +{ + private: + bool FunctionPointerType; + void (*FunctionPointer)(); + unsigned char* ObjectPointer; + unsigned char* MethodPointer; + void (GenericFunctionHandler::*InvokePointer)(); + + template<class Class> + void InvokeMethod() + { + (*(Class**)ObjectPointer->**(void (Class::**)())MethodPointer)(); + } + + public: + GenericFunctionHandler(void (*FunctionAddress)()) + : FunctionPointerType(0), FunctionPointer(FunctionAddress) + { + } + template<class Class> + GenericFunctionHandler(Class* ObjectAddress, void (Class::*MethodAddress)()) : + FunctionPointerType(1), ObjectPointer(new unsigned char(sizeof(ObjectAddress))), + MethodPointer(new unsigned char(sizeof(MethodAddress))), + InvokePointer(&GenericFunctionHandler::InvokeMethod<Class>) + { + memcpy(ObjectPointer, (unsigned char*)&ObjectAddress, sizeof(ObjectAddress)); + memcpy(MethodPointer, (unsigned char*)&MethodAddress, sizeof(MethodAddress)); + } + + ~GenericFunctionHandler() + { + delete[] ObjectPointer; + delete[] MethodPointer; + } + + void Call() + { + if (!FunctionPointerType) + { + (*FunctionPointer)(); + } + else + { + (this->*InvokePointer)(); + } + } + + void operator ()() + { + if (!FunctionPointerType) + { + (*FunctionPointer)(); + } + else + { + (this->*InvokePointer)(); + } + } +}; + +#endif \ No newline at end of file