Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.
|
|
Kwok
Posts:
8
Registered:
5/31/12
|
|
create object in C++ mex S-function
Posted:
Nov 26, 2012 11:11 AM
|
|
When I create object of a class by calling myClass* p_myClass = new myClass(); outside all the S-function method, it will work for the first run. When I run the model again, it outputs a really small number, which doesn't seem to work properly. When I put create the object and store the pointer using PWork vector inside mdlStart, it works. What is the difference? Below is my simple code to test this.
#define S_FUNCTION_LEVEL 2 #define S_FUNCTION_NAME test_1 #include "simstruc.h" #include "myClass.h" #define NumInput 0 #define NumOutput 1
// this does not work properly myClass* p_myClass = new myClass();
static void mdlInitializeSizes(SimStruct *S){ int PortIndex; ssSetNumSFcnParams(S, 0); /* Number of expected parameters */ if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) { /* Return if number of expected != number of actual parameters */ return; } ssSetNumContStates(S, 0); ssSetNumDiscStates(S, 0); // InputPort if (!ssSetNumInputPorts(S, NumInput)) return; //no input // OutputPort if (!ssSetNumOutputPorts(S, NumOutput)) return; for (PortIndex=0; PortIndex<NumOutput; PortIndex++){ ssSetOutputPortWidth(S, PortIndex, 1); } ssSetNumSampleTimes(S, 1); ssSetNumPWork( S, 1); ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE); ssSetOptions(S, 0); }
static void mdlInitializeSampleTimes(SimStruct *S){ ssSetSampleTime(S, 0, CONTINUOUS_SAMPLE_TIME); ssSetOffsetTime(S, 0, 0.0); }
#define MDL_START #if defined(MDL_START) static void mdlStart(SimStruct *S){ // This will work properly. //myClass* p_myClass = new myClass(); ssGetPWork(S)[0] = (void *) p_myClass; } #endif
static void mdlOutputs(SimStruct *S, int_T tid) { myClass* p_myClass = (myClass *) ssGetPWork(S)[0]; real_T *y0 = ssGetOutputPortRealSignal(S,0); y0[0]=p_myClass->GetVar1(); }
static void mdlTerminate(SimStruct *S){ myClass* p_myClass = (myClass *) ssGetPWork(S)[0]; delete p_myClass; }
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */ #include "simulink.c" /* MEX-file interface mechanism */ #else #include "cg_sfun.h" /* Code generation registration function */ #endif
----------------------------------------------------------------------------------------------------- class myClass{ private: double var1; int var2; double* ptr; public: myClass(); ~myClass(); double GetVar1(){ return var1; } int GetVar2(){ return var2; } double AddVariable(){ return var1+double(var2); } double GetEntry2(){ return ptr[1]; } };
myClass::myClass(){ var1=2.55; var2=5; ptr = new double [3]; for(int count=0;count<3;count++){ ptr[count]=count*10+1000; } }
myClass::~myClass(){ printf("deleted allocated memory\n"); delete[] ptr; }
|
|
|
|