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 /** A class for storing and calling a pointer to a static or member void function
25 class FunctionPointer
{
28 /** Create a FunctionPointer, attaching a static function
30 * @param function The void static function to attach (default is none)
32 FunctionPointer(void (*function
)(void) = 0);
34 /** Create a FunctionPointer, attaching a member function
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
40 FunctionPointer(T
*object
, void (T::*member
)(void)) {
41 attach(object
, member
);
44 /** Attach a static function
46 * @param function The void static function to attach (default is none)
48 void attach(void (*function
)(void) = 0);
50 /** Attach a member function
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
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
>;
63 /** Call the attached static or member function
69 static void membercaller(void *object
, char *member
) {
70 T
* o
= static_cast<T
*>(object
);
72 memcpy((char*)&m
, member
, sizeof(m
));
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