User`s guide

3 Writing S-Functions As C-MEX files
3-2
Introduction
A C MEX-file that definesan 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 incl ude d efining initial conditions and block characteristics, and
computing derivatives, discrete states, and outputs.
C MEX-file S-functions have the same structure and perform the same
functions as M-file S-functions. In addition, C MEX S-functions provide you
with more functio nality than M-file S- functions. Simulink includes a template
file for writing C MEX S-functions, called
sfuntmpl.c and a more complete
version called
sfuntmpl.doc (both located in simulink/src).
The general format of a C MEX S-function is shown below:
#define S_FUNCTION_NAME your_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. There are several other
mdl* routines within an S-function. All
S-functionsmust conform to this format. This means that differentS -functions
can implemented using S-function routines of the same name but different