1 /* mbed Microcontroller Library
2 * Copyright (c) 2006-2013 ARM Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 #ifndef MBED_FUNCTIONPOINTER_H
17 #define MBED_FUNCTIONPOINTER_H
23 typedef void (*pvoidf_t)(void);
25 /** A class for storing and calling a pointer to a static or member void function
27 class FunctionPointer {
30 /** Create a FunctionPointer, attaching a static function
32 * @param function The void static function to attach (default is none)
34 FunctionPointer(void (*function)(void) = 0);
36 /** Create a FunctionPointer, attaching a member function
38 * @param object The object pointer to invoke the member function on (i.e. the this pointer)
39 * @param function The address of the void member function to attach
42 FunctionPointer(T *object, void (T::*member)(void)) {
43 attach(object, member);
46 /** Attach a static function
48 * @param function The void static function to attach (default is none)
50 void attach(void (*function)(void) = 0);
52 /** Attach a member function
54 * @param object The object pointer to invoke the member function on (i.e. the this pointer)
55 * @param function The address of the void member function to attach
58 void attach(T *object, void (T::*member)(void)) {
59 _object = static_cast<void*>(object);
60 memcpy(_member, (char*)&member, sizeof(member));
61 _membercaller = &FunctionPointer::membercaller<T>;
65 /** Call the attached static or member function
69 pvoidf_t get_function() const {
70 return (pvoidf_t)_function;
74 void operator ()(void);
79 static void membercaller(void *object, char *member) {
80 T* o = static_cast<T*>(object);
82 memcpy((char*)&m, member, sizeof(m));
86 void (*_function)(void); // static function pointer - 0 if none attached
87 void *_object; // object this pointer - 0 if none attached
88 char _member[16]; // raw member function pointer storage - converted back by registered _membercaller
89 void (*_membercaller)(void*, char*); // registered membercaller function to convert back and call _member on _object