This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

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