MATLAB: How does a C-MEX S-function manage its memory when there are multiple instances of it in a model

globalinputinstancesmultiples-functionsamesignalsimulinkvariables

I have a C-MEX S-function that contains numerous global variables. After compiling the S-function in question, I instantiate two copies of it in a Simulink model. Each instantiation (block) receives the same input signal, but a different set of parameters are passed to each instance of the S-function. When I run the model, I expect to see different outputs, but I see the same output from both blocks. Why is this the case?  

Best Answer

This is because instances of an S-function share memory. For a given S-function, all of its instances reference the same DLL, thus resulting in a shared memory space. For the instances to have a separate memory, you would need to provide different inputs to the instance (which does not seem to be the case in your model) or instantiate a new DWork vector to store the data. Additionally, it seems like having global variables was not the main cause of the behavior you were observing.
As a workaround, I would suggest creating a clone of the original S-function, renaming it and adding it to the model. This should result in different outputs.