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

1 回表示 (過去 30 日間)
Alireza
Alireza 2012 年 10 月 31 日
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

採用された回答

Kaustubha Govind
Kaustubha Govind 2012 年 11 月 6 日
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 件のコメント
Alireza
Alireza 2012 年 11 月 19 日
Thank you very much for your reply. Your advise has solved the problem.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSimulink Functions についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by