If you're writing an external library to be called from Maple, then you have the following problem. The user wants to interrupt your code. They are valiantly pressing control-C or the stop button in the Maple GUI, as your code grinds their machine to a halt. What do you do ?

The OpenMaple C API (see ?OpenMaple,C,API) has a function called MapleCheckInterrupt, which checks for interrupt requests. You can use it in your code as follows:

#include <maplec.h>

ALGEB test(MKernelVector kv, ALGEB *args)
{
M_INT i, n = 10000000;
for (i=0; i < n; i++) {
MapleCheckInterrupt(kv);
}
return (ALGEB)1;
}

However when an interrupt occurs, MapleCheckInterrupt never returns. It passes control back to the Maple kernel. This is a problem if you have allocated memory using malloc. You need the kernel to return control to you so that you can free memory and clean up. Here is the solution that I use:

#include <maplec.h>

M_BOOL check_interrupt(MKernelVector kv)
{
M_BOOL e;
kv->traperror((void *)kv->checkInterrupt, NULL, &e);
return e;
}

ALGEB test(MKernelVector kv, ALGEB *args)
{
M_INT i, *x, n = 10000000;
x = malloc(n*sizeof(M_INT));
for (i=0; i < n; i++) {
if (check_interrupt(kv)) {
free(x);
kv->error("Interrupted");
}
}
free(x);
return (ALGEB)1;
}

The check_interrupt function uses the kernel to trap it's own error. It's not fast or pretty, but it works.


Please Wait...