MATLAB: How to allocate and free memory for a PWork vector in a C-MEX S-function

allocatec - mexfreememorypworks-functionsimulinkspecify

How do I allocate and free memory for a PWork vector in a C-MEX S-function?

Best Answer

First, the S-Function needs to specify how many PWork vectors it needs (using ssSetNumPWork) either in mdlInitializeSizes or in mdlSetWorkWidths. Simulink calls the above functions in the S-Function at the beginning of the model initialization stage (internally we refer to this part of the initialization stage as the compile phase). Towards the end of model initialization stage (internally we refer to this part of the initialization stage as the link phase), Simulink allocates the specified number of PWorks. Upon completing the model initialization stage, Simulink calls the S-Function's mdlStart. In the mdlStart function, the S-Function can allocate memory and store a pointer to it in the PWork array. The following code snippet illustrates specifying, allocating, using, and freeing memory using PWorks.
 
mdlInitializeSizes(SimStruct* S)
{
/* snip */
ssSetNumPWork(S, 1);
/* snip */
}
mdlStart(SimStruct* S)
{
/* snip */
void* ptr = malloc(1024 /* number of bytes */);
if (ptr == NULL) {
/* report memory allocation error */
ssSetErrorStatus(S, "Memory allocation error");
return;
}
ssSetPWorkValue(S, 0, ptr);
/* snip */
}
mdlOutputs(SimStruct* S, int_T tid)
{
void* ptr = ssGetPWorkValue(S, 0);
/* snip */
}
mdlTerminate(SimStruct* S)
{
/* snip */
/* free the memory allocated in mdlStart */
if (ssGetPWork(S) != NULL) {
void* ptr = ssGetPWorkVale(S,0);
if (ptr != NULL) free(ptr);
}
/* snip */
}
For a more complete example on using PWork vectors please look at the following example in the documentation.