问题
Is there a way to share a C structure (instantiated only once) among several C S-functions? Here's what I mean: I have a Simulink model with many blocks that are implemented as C S-functions. There are many model parameters that are needed in those blocks and I would like to create a single object that holds all model parameters and is instantiated only once when I start the simulation. Right now I instantiate this object for each S-function in order to access the parameters but it would be nice to share this object among the S-functions.
Just a pure guess: Could I place my model parameters structure in a separate DLL and access it afterwards from each C S-function? Has any of you done this before?
回答1:
I have successfully implemented and tested the DLL idea (i.e. gather all model parameters in a struct inside a DLL - plus any necessary calculations - and link it to other C S-functions). Simulink is a single process and I believe the simulation is a single thread (if not there are ways to make it thread-safe).
The structure with model parameters from the DLL acts as a singleton (instantiated only once per simulation and shared among other S-functions).
Update (some replies from mathworks):
The simulation part from Simulink is always single threaded. Hence, there are no thread-safety concerns for the shared DLL.
The global variables for the different S-function blocks would share the same memory location. This implies that a single instance of the shared library will be loaded for all of Simulink. Therefore all S-function instances that load the shared library will be referring to the same shared library and data.
Alternatively you can also consider using the Data Store Blocks to implement global variables. This will require a signal connection from each S-function to the appropriate Data Store Blocks. But a connection between S-functions would not be needed.
回答2:
You could allocate and store the values in a separate DLL, although it seems complicated. Sharing DLLs between s-functions a few years ago, I found Matlab/Simulink's DLL loading to be opaque and hard to manage (e.g. loading dependent DLLs).
A simpler approach - have one s-function allocate the structs in its DWork vector :
http://www.mathworks.com/help/simulink/sfg/about-dwork-vectors.html
then store the pointer values to some workspace / global variables, where they can be accessed later on by the other s-functions.
Probably the easiest way to write to workspace / global variables using mexEvalString, and to read from them using mexGetVariable (Mathworks documentation is great for these and other functions)
来源:https://stackoverflow.com/questions/17966799/how-to-share-a-c-struct-among-c-s-functions