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

1 view (last 30 days)
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

Accepted Answer

Kaustubha Govind
Kaustubha Govind on 6 Nov 2012
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.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!