Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

why Matlab crashed when I use persistent C++ COM Object in Sfunction?

Asked by Alireza on 31 Oct 2012

Dear all, I have put the following codes inside mdlStart and mdlOutput. Wehn I run Simulink model containing this Level 2 C++ Sfunction, Matlab crashes with and error of "Segmentation violation". If I remove method call in mdlOutputs, the program works. In mdlStart I can call any methods of the COM object and they work fine.

    class ISWrapper
    {
    //A COM wrapper class which wraps a COM Object Class named ISClass.
    }
      static void mdlInitializeSizes(SimStruct *S)
      {...
            ssSetNumPWork(S, 1);
      ...}
      static void mdlStart(SimStruct *S)
      {
      CoInitialize(NULL);	
      ISWrapper Iw; //definition of Wrapper class Instance
      ssGetPWorkValue(S,0)= (void *) Iw.GetPtr(); 
        //Method Getptr of ISWrapper Class construct a COM Object of
        //ISClass interface class and returns the Pointer to it
      (* (ISClass *) ssGetPWorkValue(S,0)).Connect();
      (* (ISClass *) ssGetPWorkValue(S,0)).SetMode(1);
       // these two methods works fine here
  }
static void mdlOutputs(SimStruct *S, int_T tid)
{
    const real_T *u = (const real_T*) ssGetInputPortSignal(S,0);
    real_T    *y = (real_T *) ssGetOutputPortSignal(S,0);
   //*********** This line make crash
    (* (ISClass *) ssGetPWorkValue(S,0)).Connect();
   //**********
}

If I call exactly the same methods as called above in mdlOutputs, Matlab crashes. The line which make crash in mdlOutputs is exactly the same which is work correctly in mdlStart. Both of them use Pwork vector as the pointer to the persistent COM object, why the second call to the same object method make a crash? Can anybody help? Thank you

0 Comments

Alireza

Products

1 Answer

Answer by Kaustubha Govind on 6 Nov 2012
Accepted answer

I suspect it is because your declaration of the variable ISWrapper Iw; goes out of scope at the end of mdlStart. Perhaps you should instead write something like:

      static void mdlStart(SimStruct *S)
      {
         CoInitialize(NULL);	
         ssSetPWorkValue(S, 0, (void *) (new ISWrapper)); 
      }
      static void mdlOutputs(SimStruct *S, int_T tid)
      {
         const real_T *u = (const real_T*) ssGetInputPortSignal(S,0);
         real_T    *y = (real_T *) ssGetOutputPortSignal(S,0);
         ISWrapper* Iw = (ISWrapper*)ssGetPWorkValue(S,0);
         Iw->GetPtr()->Connect();
      }

Don't forget to delete the ISWrapper pointer in mdlTerminate.

1 Comment

Alireza on 19 Nov 2012

Thank you very much for your reply. Your advise has solved the problem.

Kaustubha Govind

Contact us