MATLAB: Do I get a stack overflow exception when I debug a GRT executable containing Embedded MATLAB blocks using Microsoft Visual Studio

simulink coder

I have a comparatively large model containing Embedded MATLAB blocks, into which I pass structures consisting of large arrays. When I increase the size of the arrays, the executable generated by the GRT system target file is created successfully using Real-Time Workshop 7.1 (R2008a). However, on running the executable, it fails and returns a negative value as status.
This same model throws the following error during simulation in the Rapid Accelerator Mode although it runs normally in the Normal and Accelerator Modes:
Error occurred while executing External Mode MEX-file 'ext_comm':
ExtGetTargetPkt() call failed while checking target pkt header.

Best Answer

This behavior is observed because structures are not passed by reference in the code generated for Embedded MATLAB Function blocks, thus causing the C compiler to throw exceptions when the structures are very large.
As a workaround, one of the following suggestions may be implemented:
1. Use the eml.inline('always') directive in Embedded MATLAB Functions, in order to ensure that there are no function calls and thus no large structures being passed by value, leading to stack overflow.
2. Change the type of the parameter from structure to a matrix. Embedded MATLAB passes matrices by reference, thereby reducing the stack size.
3. Use the A=foo(A) pattern to force the structure to be passed by reference - every time a structure is passed to a function, use the following format:
[otherOutputs ... , A] = function_name(otherInputs, ... A)
Whenever Embedded MATLAB sees a function that receives a parameter and then returns it, it optimizes the function so that the parameter is passed by reference. This is the desired effect and will reduce the stack size.
Note that, in this case, the error seen when running the model in Rapid Accelerator Mode was due to the stack overflow. However, a stack overflow error does not necessarily always lead to a packet error or vice-versa.