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

4 visualizzazioni (ultimi 30 giorni)
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 ?

Risposta accettata

Shishir Reddy
Shishir Reddy il 27 Giu 2025
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.

Più risposte (0)

Categorie

Scopri di più su Simulink Coder in Help Center e File Exchange

Prodotti


Release

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by