c++cmicrocontrollerinterruptmsp432

How to write C++ ISR with MSP432 DriverLib'c C code?


I want to use C++ as my main programming language for my microcontroller (MSP432) projects.

I wrote some simple scripts not involving interrupt service routines (ISR). They all worked fine. The code had looked like the following:

/* MSP and DriverLib includes */
/* no <<extern "C">> needed due to the header files implement it. */
#include <ti/devices/msp432p4xx/driverlib/driverlib.h>

int main()
{
    /* Some C++ code here that worked fine. */
}

Now I wanted to upgrade my code to have simple ISR like for UART communication (serial PC interface). So I did this:

/* MSP and DriverLib includes */
/* no <<extern "C">> needed due to the header files implement it. */
#include <ti/devices/msp432p4xx/driverlib/driverlib.h>

int main()
{
    /* Some C++ code here that worked fine. */
}

void EUSCIA0_IRQHandler(void)
{
    /* Some C++ code here that worked fine. */
}

The issue with this code is that the ISR is not get triggered. Instead the default ISR from the DriverLib is called. I wondered and started to try digging myself.

At some point I accidentally put extern "C" around the ISR defined in the C++ part of the source code. And it worked:

/* MSP and DriverLib includes */
/* no <<extern "C">> needed due to the header files implement it. */
#include <ti/devices/msp432p4xx/driverlib/driverlib.h>

int main()
{
    /* Some C++ code here that worked fine. */
}

extern "C"
{

    void EUSCIA0_IRQHandler(void)
    {
        /* Only C code here works fine. */
    }

}

I assume since "I" (DriverLib) registered the ISR vectors and extern ISR signatures in the C (not the C++) part of the source code, my C++ ISR is some kind out of scope for the ISR signature..

1) Am I right?

But there is a catch. Since I moved my C++ ISR into C context I am not able to use C++ code e.g. classes etc. anymore within the ISR.

2) How to keep C++ within the ISR within the C++ part of the source code without touching DriverLib's ISR initialization (e.g. startup_msp432p401r_ccs.c)?


Solution

  • If the driver library is static (i.e. .a), you can do:

    extern "C" void EUSCIA0_IRQHandler(void)
    {
        // whatever ...
    }
    

    This should replace the standard function with yours [which you can check with nm, etc.]. And, when the driver library registers the ISR function, it should catch yours instead of its internal one

    I believe you can now call c++ code from this function.


    If not, you may need:

    void cplus_plus_handler(void)
    {
        // whatever ...
    }
    
    extern "C" void EUSCIA0_IRQHandler(void)
    {
        cplus_plus_handler();
    }
    

    This probably works as is. But, cplus_plus_handler may need to be in a separate .cpp file [with the C handler in a .c].


    If the library is dynamic (i.e. .so, .dll), you may need to call a registration function to attach your ISR function.