In Simulink, if I have a C++ S-function with classes containing static attributes, will multiple instances of the S-function cause problems between the static variables?

4 views (last 30 days)
I have written an S-function with a C++ class. The class has static attributes in it. If I have multiple copies of the S-function, will changes to the static attributes affect the rest of the S-function instances?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Oct 2013
If there are multiple instances of the same S-function in the model, there is only one .dll loaded into Simulink memory. So, if there are any classes that use static variables, if the first instance of the S-function changes those static variables, the next instance gets those changed values. In this case, there would only be one pool of memory for the S-function to work with, so the "static-ness" of the variables spans across all of the blocks in the model.
There are two ways around this:
1. The first is to rename the S-function for each instance of the S-function block. This will allow for a separate .dll for each instance and thus separate static variables for each instance. In this case however, if, you are generating a standalone executable from this model (using say grt.tlc), you need the custom code to be linked as many times as there are instances in the "Custom Code" pane inside the "Configuration Parameters" dialog.
2. The second is to use work vectors. Work vectors exist separately for each instance of the S-function block even if there are multiple copies of the S-function block in the model.
If each S-Function block is expected to be unique(i.e. behave like any other Simulink block), the user needs to make sure that static variables, if any, are not read and modifed by different instances of it in the same model. Conversely, if they are expecting all S-functions to share the same memory space, then this is easier if they do not use work vectors (which will not be shared).

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!