Writing S-Functions    

Exception Free Code

You can avoid this overhead by ensuring that your S-function contains entirely exception free code. Exception free code refers to code that never long jumps. Your S-function is not exception free if it contains any routine that, when called, has the potential of long jumping. For example mexErrMsgTxt throws an exception (i.e., long jumps) when called, thus ending execution of your S-function. Using mxCalloc may cause unpredictable results in the event of a memory allocation error since mxCalloc will long jump. If memory allocation is needed, use the stdlib.h calloc routine directly and perform your own error handling.

If you do not call mexErrMsgTxt or other API routines that cause exceptions, then use the SS_OPTION_EXCEPTION_FREE_CODE S-function option. This is done by issuing the following command in the mdlInitializeSizes function.

Setting this option will increase the performance of your S-function by allowing Simulink to bypass the exception handling setup that is usually performed prior to each S-function invocation. Extreme care must be taken to verify that your code is exception free when using SS_OPTION_EXCEPTION_FREE_CODE. If your S-function generates an exception when this option is set, unpredictable results will occur.

All mex* routines have the potential of long jumping. In addition several mx* routines have the potential of long jumping. To avoid any difficulties, use only the API routines that retrieve a pointer or determine the size of parameters. For example, the following will never throw an exception: mxGetPr, mxGetData, mxGetNumberOfDimensions, mxGetM, mxGetN, and mxGetNumberOfElements.

Code in run-time routines can also throw exceptions. Run-time routines refer to certain S-function routines that Simulink calls during the simulation loop (see How Simulink Interacts with C S-Functions). The run-time routines include:

If all run-time routines within your S-function are exception free, you can use this option.

The other routines in your S-function do not have to be exception free.


 Handling Errors ssSetErrorStatus Termination Criteria