MATLAB: How to access a single instance of the C++ object from several S-Functions in Simulink 7.1 (R2008a)

simulink

I have a C++ class with several methods that I am creating S-Functions for. I want to be able to create an instance of the class and then have each of my S-Functions use that instance during simulation. I would like to know how I may accomplish this task.

Best Answer

You cannot access a single instance of your C++ object between different S-Functions but you can share access to a single object between multiple instances of a single S-function. Attached is a modified version of the C++ 'Counter' S-Function demo (sfncdemo_counter_cpp.mdl) that uses the STATIC keyword to create a single instance of the counter class that is accessed by both instances of the S-Function.
In the original file the Start and Output functions are written as follows:
#define MDL_START /* Change to #undef to remove function */
#if defined(MDL_START)
/* Function: mdlStart =======================================================
* Abstract:
* This function is called once at start of model execution. If you
* have states that should be initialized once, this is the place
* to do it.
*/
static void mdlStart(SimStruct *S)
{
ssGetPWork(S)[0] = (void *) new counter; // store new C++ object in the
} // pointers vector
#endif /* MDL_START */
/* Function: mdlOutputs =======================================================
* Abstract:
* In this function, you compute the outputs of your S-function
* block.
*/
static void mdlOutputs(SimStruct *S, int_T tid)
{
counter *c = (counter *) ssGetPWork(S)[0];
real_T *y = ssGetOutputPortRealSignal(S,0); // the pointers vector and use
y[0] = c->output(); // member functions of the
UNUSED_ARG(tid); // object
}
The modified version replaces the line
counter *c = (counter *) ssGetPWork(S)[0];
with
static counter *c = (counter *) ssGetPWork(S)[0];
The "static" keyword prevents the creation of a second counter by the second instance of the S-Function block.