svn / mbed / trunk / FunctionPointer.h

Revision 29, 2.3 kB (checked in by emilmont, 6 months ago)

New Libraries 11.11

Line 
1/* mbed Microcontroller Library - FunctionPointer
2 * Copyright (c) 2007-2009 ARM Limited. All rights reserved.
3 */ 
4 
5#ifndef MBED_FUNCTIONPOINTER_H
6#define MBED_FUNCTIONPOINTER_H
7
8#include <string.h>
9
10namespace mbed { 
11
12/* Class FunctionPointer
13 *  A class for storing and calling a pointer to a static or member void function
14 */
15class FunctionPointer {
16
17public:
18
19    /* Constructor FunctionPointer
20     *  Create a FunctionPointer, attaching a static function
21     *
22     * Variables
23     *  function - The void static function to attach (default is none)
24     */
25    FunctionPointer(void (*function)(void) = 0);
26
27    /* Constructor FunctionPointer
28     *  Create a FunctionPointer, attaching a member function
29     *
30     * Variables
31     *  object - The object pointer to invoke the member function on (i.e. the this pointer)
32     *  function - The address of the void member function to attach
33     */
34    template<typename T>   
35    FunctionPointer(T *object, void (T::*member)(void)) {
36        attach(object, member);
37    }
38
39    /* Function attach
40     *  Attach a static function
41     *
42     * Variables
43     *  function - The void static function to attach (default is none)
44     */
45    void attach(void (*function)(void) = 0);
46   
47    /* Function attach
48     *  Attach a member function
49     *
50     * Variables
51     *  object - The object pointer to invoke the member function on (i.e. the this pointer)
52     *  function - The address of the void member function to attach
53     */
54    template<typename T>
55    void attach(T *object, void (T::*member)(void)) {
56        _object = static_cast<void*>(object);
57        memcpy(_member, (char*)&member, sizeof(member));
58        _membercaller = &FunctionPointer::membercaller<T>;
59        _function = 0;
60    }
61
62    /* Function call
63     *  Call the attached static or member function
64     */     
65    void call();
66       
67private:
68
69    template<typename T>
70    static void membercaller(void *object, char *member) { 
71        T* o = static_cast<T*>(object);
72        void (T::*m)(void);
73        memcpy((char*)&m, member, sizeof(m));
74        (o->*m)();
75    }
76   
77    void (*_function)(void);                // static function pointer - 0 if none attached
78    void *_object;                          // object this pointer - 0 if none attached
79    char _member[16];                       // raw member function pointer storage - converted back by registered _membercaller
80    void (*_membercaller)(void*, char*);    // registered membercaller function to convert back and call _member on _object
81   
82};
83
84} // namespace mbed
85
86#endif
Note: See TracBrowser for help on using the browser.