Generating c++ code from Simulink model with a mex function

조회 수: 4 (최근 30일)
Paul King
Paul King 2025년 6월 25일
댓글: Paul King 2025년 6월 30일
I am using a 3rd party library to do some optimisation in my SImulink model and I have generated a mex file for the script that I am using.
I now want to generate code c++ code for this model using the Simulink Coder. I can generate code but when I look at the resulting files I can't seem to see where all of the code is that does the optimisation.
I suspect that the code I have generated links back to the mex file that I have generated ... is this correct ?

채택된 답변

Shishir Reddy
Shishir Reddy 2025년 6월 27일
Hi Paul
When a MEX file is used in a Simulink model, the code generated by Simulink Coder does not include the optimization logic contained within the MEX file. Instead, the MEX file is treated as an external binary, and references to it are made in the generated code. As a result, the optimization logic is not visible in the C++ files produced during code generation.
If your goal is to generate portable, self-contained C++ code, relying on a MEX file does not work because MEX is specific to MATLAB and is not suitable for standalone code generation.
A more appropriate solution would be to implement the optimization logic in a C/C++ S-Function, allowing it to be integrated directly into the Simulink model. This ensures that the logic is included in the generated code. A simple example is shown below:
#define S_FUNCTION_NAME simple_opt_sfunc
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
static void mdlOutputs(SimStruct *S, int_T tid) {
real_T *y = ssGetOutputPortRealSignal(S, 0);
y[0] = perform_optimization(); // Your optimization logic should be placed here
}
#include "simulink.c"
Replace 'perform_optimization' with your own C/C++ code. Then, add this S-Function to your model using an S-Function block.
For more information regarding 'S-Function' block, kindly refer the following documentation - https://www.mathworks.com/help/simulink/slref/sfunction.html
I hope this helps.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Simulink Coder에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by