Reputation: 1580
Is it possible to write an interrupt handler in C++ for ARM Cortex chips like those of ST and NXP.
Currently I develop a lot of code in C++ for ARM cortex chips. I am a bit fed up with having to call a static/global/singleton C++ object from a C callback function. Is there a way to not having to through the C function.
Is there a way to directly call a C++ object functions when a interrupt occurs?
Upvotes: 2
Views: 2215
Reputation: 283793
It is possible to write the interrupt handler in any language that compiles to native code.
It still has to use C language linkage with the interrupt handler calling convention. That means no member functions. (Formally, static member functions are illegal as well, although they usually work in practice. Non-static member functions cannot be used.)
In C++, first enable the C language linkage with extern "C"
. Also use any compiler-specific keyword for interrupt handlers that you would have used in C, such as __interrupt
.
Inside the function you can use the full power of C++ -- objects, for-in loops, smart pointers, template instances, etc. Although you still want to be careful about how much work you do in interrupt context, and C++ tends to hide the complexity so you no longer have a feel for how many machine instructions are being generated.
On ARM Cortex M chips, there's a table of function pointers at a preset memory address. The table may be constructed in C or assembly, and if your interrupt handlers aren't exported with the correct name, the linker won't be able to find the addresses that belong in the table. C language linkage ensures that any name mangling is performed in a way compatible with the symbol references in the startup code.
Other processor families use a fixed address only for the reset vector, and install other interrupt handlers by writing each handler address into a special-function register corresponding to its interrupt. For these, only calling convention matters and not the function name/linkage. ARM Cortex-M lets you write a special function register to find the whole vector table at an alternate address, but not to relocate individual handlers.
Upvotes: 3
Reputation: 6503
Is away to directly call a C++ object function when a interrupt occurs?
In a short, no. Even if you declare your non-static method as void (void)
, it still has an implicit argument - this
. Interrupt handler on the other hand, has no arguments at all.
Upvotes: 2