Minimal Simulink S-function which takes a string as parameter
This S-function is the minimal implementation which takes a string as an S-function parameter. It is based on Matlab/Simulink: Minimal empty template S-function
Important: You need to pass the S-function parameter in single quotes ('
), passing them in double quotes does NOT work and will lead to the S-function receiving an empty string parameter.
#define S_FUNCTION_NAME string_param_sfunc
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
// Function: mdlInitializeSizes ===============================================
// Abstract:
// Setup sizes of the various vectors.
static void mdlInitializeSizes(SimStruct *S)
{
// One parameter: String
ssSetNumSFcnParams(S, 1);
}
#define MDL_START
static void mdlStart(SimStruct *S)
{
// Extract string parameter
const mxArray *param = ssGetSFcnParam(S, 0);
if(!mxIsChar(param)) {
ssSetErrorStatus(S, "Parameter is not a string!");
return;
}
const char* pCharArray = mxArrayToString(param);
printf("Extracted string parameter '%s'\n", pCharArray);
mxFree((void*)pCharArray);
}
// Function: mdlInitializeSampleTimes =========================================
// Abstract:
// Initialize the sample times to be 1ms (1kHz)
static void mdlInitializeSampleTimes(SimStruct *S)
{
// For an example what to add here, see https://techoverflow.net/2024/10/20/matlab-level-2-s-function-example-sine-wave-continous-output/
}
// Function: mdlOutputs =======================================================
// Abstract:
// Calculate the sine wave output based on the simulation time.
static void mdlOutputs(SimStruct *S, int_T tid)
{
// For an example what to add here, see https://techoverflow.net/2024/10/20/matlab-level-2-s-function-example-sine-wave-continous-output/
}
// Function: mdlTerminate =====================================================
// Abstract:
// This function is called at the end of simulation for cleanup.
static void mdlTerminate(SimStruct *S)
{
// No cleanup required for this example
}
// Required S-function trailer
#ifdef MATLAB_MEX_FILE
#include "simulink.c" // MEX-file interface mechanism
#else
#include "cg_sfun.h" // Code generation interface
#endif
Compile using
mex -g string_param_sfunc.cpp CXXFLAGS="-std=gnu++17 -fPIC"
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow