General thunking class to allow C-style callbacks to C++ class members - including optional parameters.

Dependents:   cthunk_example

Revision:
1:53a00c956d82
Parent:
0:7de85300ea3a
Child:
2:3197c4a8ba85
--- a/CThunk.h	Wed Aug 13 07:43:23 2014 +0000
+++ b/CThunk.h	Fri Aug 15 12:50:49 2014 +0000
@@ -26,15 +26,6 @@
 /* IRQ/Exception compatible thunk entry function */
 typedef void (*CThunkEntry)(void);
 
-/* template for thunk trampoline */
-#ifdef __thumb__
-#define CTHUNK_OPCODES_SIZE 8
-#else
-#error "TODO: add support for non-thumb trampoline, too"
-#endif
-
-extern const uint8_t g_cthunk_opcodes[CTHUNK_OPCODES_SIZE];
-
 template<class T>
 class CThunk
 {
@@ -42,19 +33,9 @@
         typedef void (T::*CCallbackSimple)(void);
         typedef void (T::*CCallback)(void* context);
 
-        inline CThunk(void)
+        inline CThunk(T *instance)
         {
-            /* copy ARM thumb compatible pcode preamble */
-            memcpy(
-                &m_thunk.code,
-                &g_cthunk_opcodes,
-                CTHUNK_OPCODES_SIZE
-            );
-            /* set remainder to zero */
-            memset(
-                &m_thunk.code + CTHUNK_OPCODES_SIZE,
-                0, sizeof(m_thunk.code) - CTHUNK_OPCODES_SIZE
-            );
+            init(*instance, NULL, NULL);
         }
 
         inline CThunk(T &instance)
@@ -110,25 +91,25 @@
         /* get thunk entry point for connecting rhunk to an IRQ table */
         inline operator CThunkEntry(void)
         {
-            return (CThunkEntry)&m_thunk.code;
+            return (CThunkEntry)&m_thunk;
         }
 
         /* get thunk entry point for connecting rhunk to an IRQ table */
         inline operator uint32_t(void)
         {
-            return (uint32_t)&m_thunk.code;
+            return (uint32_t)&m_thunk;
         }
 
         /* simple test function */
         inline void call(void)
         {
-            ((CThunkEntry)&m_thunk.code)();
+            ((CThunkEntry)&m_thunk)();
         }
 
     private:
         typedef struct
         {
-            uint8_t code[CTHUNK_OPCODES_SIZE];
+            uint32_t code;
             T* instance;
             void* context;
             CCallback callback;
@@ -138,11 +119,15 @@
 
         inline void init(T &instance, CCallback callback, void* context)
         {
-            memcpy(&m_thunk.code, &g_cthunk_opcodes, CTHUNK_OPCODES_SIZE);
+#ifdef __thumb2__
+            m_thunk.code = 0x8003E89F;
+#else
+#error "TODO: add support for non-cortex-m3 trampoline, too"
+#endif
             m_thunk.instance = &instance;
             m_thunk.context = context;
             m_thunk.callback = callback;
         }
 };
 
-#endif/*__CTHUNK_H__*/
\ No newline at end of file
+#endif/*__CTHUNK_H__*/