How do I work with static or global variables in CMEX S-functions? What are work vectors?

7 views (last 30 days)
For example, I would like to track the previous value of each input signal element entering one of the ports of my S-function block. I would like to obtain this type of persistent storage of variables, and I wonder if I should use static or global variables. Doing this could lead to a reentrancy problem that I would like to avoid.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Nov 2016
This enhancement has been incorporated in Release 2008a (R2008a). For previous product releases, read below for any possible workarounds:
Simulink has Work Vectors that you can allocate for storing static double, integer, and pointer variables. Work vectors allow you to create a reentrant S-function, and should be used instead of static or global variables. Work Vectors are discussed in detail with examples starting on page 7-24 of the Simulink 4.0 on-line version of the Writing S-functions Guide, available here:
To allocate storage, use the API macro ssSetNumXWork, where X could be: R for real, I for integer, or P for pointer. This is done in mdlInitializesizes.
Once allocated, you can then obtain these values using other macros, such as ssGetRWork, which returns a pointer to the allocated work vector.
This mechanism allows variables to be used in any function of the S-function, and assures the integrity of the variable, since calls between various functions using GLOBAL is not good practice.

More Answers (0)

Categories

Find more on Block and Blockset Authoring in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!