Writing S-Functions | ![]() ![]() |
Introduction
A C MEX-file that defines an S-Function block must provide information about the model to Simulink during the simulation. As the simulation proceeds, Simulink, the ODE solver, and the MEX-file interact to perform specific tasks. These tasks include defining initial conditions and block characteristics, and computing derivatives, discrete states, and outputs.
As with M-file S-functions, Simulink interacts with a C MEX-file S-function by invoking callback methods that the S-function implements. Each method performs a predefined task, such as computing block outputs, required to simulate the block whose functionality the S-function defines. Simulink defines in a general way the task of each callback. The S-function is free to perform the task according to the functionality it implements. For example, Simulink specifies that the S-function's mdlOutput
method must compute that block's outputs at the current simulation time. It does not specify what those outputs must be. This callback-based API allows you to create S-functions, and hence custom blocks, of any desired functionality.
The set of callback methods, hence functionality, that C MEX-files can implement is much larger than that available for M-file S-functions. See Chapter 9, S-Function Callback Methods for descriptions of the callback methods that a C MEX-file S-function can implement. Unlike M-file S-functions, C MEX-files can access and modify the data structure that Simulink uses internally to store information about the S-function. The ability to implement a broader set of callback methods and to access internal data structures allows C-MEX files to implement a wider set of block features, such as the ability to handle matrix signals and multiple data types.
C MEX-file S-functions are required to implement only a small subset of the callback methods that Simulink defines. If your block does not implement a particular feature, such as matrix signals, you are free to omit the callback methods required to implement a feature. This allows you to create simple blocks very quickly.
The general format of a C MEX S-function is shown below.
#define S_FUNCTION_NAMEyour_sfunction_name_here
#define S_FUNCTION_LEVEL 2 #include "simstruc.h" static void mdlInitializeSizes(SimStruct *S) { }<additional S-function routines/code>
static void mdlTerminate(SimStruct *S) { } #ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */ #include "simulink.c" /* MEX-file interface mechanism */ #else #include "cg_sfun.h" /* Code generation registration function */ #endif
mdlInitializeSizes
is the first routine Simulink calls when interacting with the S-function. Simulink subsequently invokes other S-function methods (all starting with mdl
). At the end of a simulation, Simulink calls mdlTerminate
.
![]() | Processing S-Function Parameters | Example of a Basic C MEX S-Function | ![]() |