Contents

Make C++ Objects Persistent

Your C++ callback methods might need to create persistent C++ objects, that is, objects that continue to exist after the method exits. For example, a callback method might need to access an object created during a previous invocation. Or one callback method might need to access an object created by another callback method. To create persistent C++ objects in your S-function:

  1. Create a pointer work vector to hold pointers to the persistent object between method invocations:

    static void mdlInitializeSizes(SimStruct *S)
    {
        ...
    		ssSetNumPWork(S, 1); // reserve element in the pointers vector
                             // to store a C++ object
        ...
     }
    
  2. Store a pointer to each object that you want to be persistent in the pointer work vector:

      static void mdlStart(SimStruct *S)
      {
          ssGetPWork(S)[0] = (void *) new counter; // store new C++ object in the
      }                                            // pointers vector
    
  3. Retrieve the pointer in any subsequent method invocation to access the object:

    static void mdlOutputs(SimStruct *S, int_T tid)
    {
        counter *c = (counter *) ssGetPWork(S)[0];   // retrieve C++ object from
        real_T  *y = ssGetOutputPortRealSignal(S,0); // the pointers vector and
        y[0] = c->output();                          // use member functions of
    }                                                // the object
    
  4. Destroy the objects when the simulation terminates:

    static void mdlTerminate(SimStruct *S)
    {
        counter *c = (counter *) ssGetPWork(S)[0]; // retrieve and destroy C++
        delete c;                                  // object in the termination
    }                                              // function
    
Was this topic helpful?