Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a compile-time array of interrupt handlers in C++?

Tags:

c++

I'd like to be able to write my ISR in one place:

some_collection TimerHandlers;    

// added to ISR table in linker script
void rawTimerIRQHandler() {
    call_each_handler_in(handlers);
}

Such that I can then register handlers in other files

// file1.cpp
void ledTimerHandler1() {

}
register(ledTimerHandler1); //or in an init function if not possible here
// file2.cpp
void ledTimerHandler2() {

}
register(ledTimerHandler2); //or in an init function if not possible here

And when the hardware jumps to rawTimerIRQHandler, it executes ledTimerHandler1 and ledTimerHandler2 in some arbitrary order.


Obviously, I can implement this using something similar to a vector<void(*)()>, but since the number of these handlers is known at compile-time, is there any way I can generate an array (or template linked list) at compile-time? I'd like to avoid the dynamic memory allocation that comes with vector.

I'm open to using template<>, #define, or even GCC-specific attributes to acheive this goal.

like image 323
Eric Avatar asked Feb 28 '13 17:02

Eric


2 Answers

The scaffolding's a bit tedious but once it's done the usage couldn't be simpler:

// example.h:
#include "Registered.h"
struct example : Registered<example> {};
// main.cc:
#include <iostream>
#include "example.h"

int main ()
{
    for ( auto p = example::registry; p; p=p->chain )
        std::cout << p << '\n';
}
// Registered.h : 
template<class registered>
struct Registered {
     static registered *registry;
     registered *chain;
     Registered() : chain(registry) {registry=static_cast<registered*>(this);}
};
// example.cc:
#include "example.h"
template<> example *Registered<example>::registry = 0;

static struct example first, second, third;  // these can be defined anywhere w/ static duration

edit: moved the first,second,third declaration/definitions to satisfy my inner pedant

like image 58
jthill Avatar answered Sep 21 '22 23:09

jthill


Absolutley. If I understand correctly, you just want a fixed array of function pointers to your handlers. Using C++11 syntax, and assuming 3 handlers just for the sake of the example,

#include <array>

const std::array<HandlerPtr, 3> handlers= {&ledTimerHandler1, &ledTimerHandler2, &ledTimerHandler3};

or using more classic C/C++ syntax

const HandlerPtr handlers[] = {&ledTimerHandler1, &ledTimerHandler2, &ledTimerHandler3};
like image 40
Matt Kline Avatar answered Sep 22 '22 23:09

Matt Kline