Search code examples
matlabsimulinkmatlab-coder

Why does Simulink coder start & stop my S function when I generate code?


I have a C-MEX S-Function in a very simple model. The S-Function does a lot (it acts as a sort of device driver to get data to/from the Simulink model). When I press the generate code button, I can see from the diagnostic log that the function is started then terminated. Why is this please?

I have a log function that is called at the various stages of the S-Function to help with me understanding the program flow, as you can see from the build log (the 3 lines starting with [INFO]):

### Generating code into build folder: /some_dir_path/output/test_grt_rtw
[INFO] mdlInitializeSizes
[INFO] mdlInitializeSampleTimes
[INFO] mdlTerminate
### Invoking Target Language Compiler on test.rtw
### Using System Target File: /Applications/MATLAB_R2015b.app/rtw/c/grt/grt.tlc
### Loading TLC function libraries
### Initial pass through model to cache user defined code
### Caching model source code
### Writing header file test.h
### Writing header file test_types.h
### Writing header file rtwtypes.h
.
### Writing header file multiword_types.h
### Writing source file test.cpp
### Writing header file test_private.h
### Writing header file rtmodel.h
### Writing source file test_data.cpp
### Writing header file rt_nonfinite.h
.
### Writing source file rt_nonfinite.cpp
### Writing header file rtGetInf.h
### Writing source file rtGetInf.cpp
### Writing header file rtGetNaN.h
### Writing source file rtGetNaN.cpp
### TLC code generation complete.
### Creating project marker file: rtw_proj.tmw
### Using toolchain: Clang v3.1 | gmake (64-bit Mac)
// remainder of log file here

Solution

  • When you generate code from a model, it is for a particular configuration of the model. While the model can be run with many different configurations, the generated code will have the sizes, types, rates and complexity of each block integrated into the code. So, to generate this code Simulink needs to propagate the types in the model to identify all the input and output specifications needed for generated code. Your S-Function code is run to determine this. The functions called should be same as a regular model run except the output computation parts are not run.

    The following document page shows what gets called in code generation for an S-Function. http://www.mathworks.com/help/simulink/sfg/how-the-simulink-engine-interacts-with-c-s-functions.html