MATLAB: Can I use C MEX Functions such as ‘mxPutVariable’ in an S-Function and then generate code

%sapiccoderfunctionmexmexputvariables-functionsimulinksimulink coder

I am trying to use C MEX API functions in my S-Function, but I am getting undefined reference compile errors when I don't include 'mex.h", and redefinition compile errors when I include "mex.h". I see that the required "simstruc.h" does include "mex.h". What is causing these errors and how can I use these functions in generated code?

Best Answer

Using C MEX API functions such as "mexPutVariable" that interact with MATLAB is not supported for code generation, because deployed generated code cannot interact with MATLAB, and MATLAB may not even be installed on the target machine. This is the cause of the compile errors. If you take a look at "simstruc.h", you will see that "mex.h" is only included if the S-Function is being used in simulation, and not in code generation. This reflects the point that the generated code has no method of interacting with MATLAB through these functions, but works fine in simulation as MATLAB is running in that case.
The following doc page has a list of all the MATLAB API functions that are supported for code generation: