Search code examples
c++matlababort

How do I abort a MATLAB m-file function from C/C++?


I deployed a MATLAB project into a DLL, to be called from C++, and it works just fine. Happy days.

But what happens when the user asks to cancel an operation?

I tried creating a global variable named UserAborted. I initialize it to 0 before running the long function in MATLAB. I also wrote the following two functions:

function AbortIfUserRequested
    global UserAborted

    if (UserAborted == 1)
        error('User Abort');
    end
end

function UserAbortLongFunction
    global UserAborted

    UserAborted = 1;
end

I call upon AbortIfUserRequested in every iteration of the loop in my long function. I also exported UserAbortLongFunction.

I expected that pretty soon after called UserAbortLongFunction, the long function would reach a call to AbortIfUserRequested, and throw an error.

Instead, the long function keeps running until the end, and only then does the value of UserAborted get changed.

All I want to do is abort that long function when the user asks me to! Is there any way to do that?


Solution

  • Matlab needs to provide callback functions to show execution progress and possibly halt it. A Google search shows lots of people wanting this but no implementation from Mathworks.