Update to new build system.
[clinton/Smoothieware.git] / mbed / src / cpp / FunctionPointer.h
1 /* mbed Microcontroller Library
2 * Copyright (c) 2006-2013 ARM Limited
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16 #ifndef MBED_FUNCTIONPOINTER_H
17 #define MBED_FUNCTIONPOINTER_H
18
19 #include <string.h>
20
21 namespace mbed {
22
23 /** A class for storing and calling a pointer to a static or member void function
24 */
25 class FunctionPointer {
26 public:
27
28 /** Create a FunctionPointer, attaching a static function
29 *
30 * @param function The void static function to attach (default is none)
31 */
32 FunctionPointer(void (*function)(void) = 0);
33
34 /** Create a FunctionPointer, attaching a member function
35 *
36 * @param object The object pointer to invoke the member function on (i.e. the this pointer)
37 * @param function The address of the void member function to attach
38 */
39 template<typename T>
40 FunctionPointer(T *object, void (T::*member)(void)) {
41 attach(object, member);
42 }
43
44 /** Attach a static function
45 *
46 * @param function The void static function to attach (default is none)
47 */
48 void attach(void (*function)(void) = 0);
49
50 /** Attach a member function
51 *
52 * @param object The object pointer to invoke the member function on (i.e. the this pointer)
53 * @param function The address of the void member function to attach
54 */
55 template<typename T>
56 void attach(T *object, void (T::*member)(void)) {
57 _object = static_cast<void*>(object);
58 memcpy(_member, (char*)&member, sizeof(member));
59 _membercaller = &FunctionPointer::membercaller<T>;
60 _function = 0;
61 }
62
63 /** Call the attached static or member function
64 */
65 void call();
66
67 private:
68 template<typename T>
69 static void membercaller(void *object, char *member) {
70 T* o = static_cast<T*>(object);
71 void (T::*m)(void);
72 memcpy((char*)&m, member, sizeof(m));
73 (o->*m)();
74 }
75
76 void (*_function)(void); // static function pointer - 0 if none attached
77 void *_object; // object this pointer - 0 if none attached
78 char _member[16]; // raw member function pointer storage - converted back by registered _membercaller
79 void (*_membercaller)(void*, char*); // registered membercaller function to convert back and call _member on _object
80 };
81
82 } // namespace mbed
83
84 #endif