필터 지우기
필터 지우기

Dynamic memory allocation in C++ S_functions

조회 수: 4 (최근 30일)
Lukas Abelt
Lukas Abelt 2017년 6월 21일
댓글: Lukas Abelt 2017년 7월 11일
Hey there, My question is pretty straightforward: Is it possible/allowed to reallocate Memory in S-functions written in C++. I have an array in my S-Function that buffers data for me and I was wondering if I need to allocate the buffer big enough in my mdlStart function or if I could start off with a small buffer and use realloc() to make it bigger if needed at run-time. While researching this Problem I found some unclear answers to that. Some say, that dynamic allocation is not allowed in Simulink, but I couldn't find any specific Information about this in the documentation. Thanks in advance
  댓글 수: 2
Dhruvesh Patel
Dhruvesh Patel 2017년 6월 28일
편집: Dhruvesh Patel 2017년 6월 28일
One option could be to use the PWORK Vector . You would need to allocate/reallocate (using malloc/realloc) in your C++ code and give the pointer to this memory to PWORK Vector which will hold on to it throughout the simulation. Refer to (2) of the following answer.
Please provide some example code describing what you intend to archive. It would lead to a more precise answer.
Lukas Abelt
Lukas Abelt 2017년 7월 11일
Hello Dhruvesh,
This is basically what I am currently doing. I am allocating my Array in the mdlStart function, store the pointer in the PWork vector and access this pointer in my mdlOutputs.
I just wanted to get some Information if the Simulink engine allows dynamic Memory (re)allocation during Simulation as some sources I found during my Research on this topic state explicitely, that dynamic Memory (re)allocation during Simulation is not allowed.
Can I assume from your post, that there are no limitations (despite the usual ones) on using malloc/realloc during Simulation?
I am attaching a snippet of my code how I allocate my buffer and store/Access it from the PWorks vector in my current Version. If possible I would like to adapt this code to dynamically allocate a greater buffer if needed (and not just use a big buffer from the beginning)
#define BUFFERSIZE 65535
...
static void mdlStart(SimStruct *S){
...
/* Allocate memory for PWork values */
void *data_buffer = calloc(BUFFERSIZE, sizeof(char));
...
ssSetPWorkValue(S, DATA_BUFFER, data_buffer);
}
...
static void mdlOutputs(SimStruct *S){
...
char *data_buffer = (char *)ssGetPWorkValue(S, DATA_BUFFER);
//Do something with data_buffer
}
//Of course free() the allocated memory in mdlTerminate()
Thank you in advance!
Lukas

댓글을 달려면 로그인하십시오.

답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by