15.2.2 Example: Copy and Modify the Default Vector Table at Runtime

This example allocates memory at runtime, duplicates the default vector table, and replaces one vector.

#include <xc.h>
#include <stdlib.h>
#include <string.h>

void __attribute__((interrupt)) my_handler(void)
{ /* do nothing */ }

void (**new_ivt)(void)  __attribute__((far));

int main()
{
  int vector_index;

  /* allocate memory for a vector table */
  new_ivt = (void (**)(void))malloc(__IVT_NUM * sizeof(void*));
  
  /* fill it from the default IVT */
  (void) memcpy(new_ivt, (const void *) IVTBASE, (__IVT_NUM * sizeof(void*)));
  
  /* replace one vector */
  vector_index = __builtin_vector_offset("__INT1Interrupt");
  new_ivt[vector_index] = &my_handler;
  
  /* install the revised IVT */
  __builtin_setIVTBASE(&new_ivt);
}