Simulink:接受字符串参数的最小 S-function
此 S-function 是接受字符串作为 S-function 参数的最小实现。它基于 Matlab/Simulink:最小空模板 S-function。
重要: 你需要用单引号(')传递 S-function 参数,用双引号传递不起作用,会导致 S-function 收到空字符串参数。

string_param_sfunc.cpp
#define S_FUNCTION_NAME string_param_sfunc
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
// Function: mdlInitializeSizes ===============================================
// Abstract:
// 设置各种向量的大小。
static void mdlInitializeSizes(SimStruct *S)
{
// 一个参数:字符串
ssSetNumSFcnParams(S, 1);
}
#define MDL_START
static void mdlStart(SimStruct *S)
{
// 提取字符串参数
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:
// 初始化采样时间为 1ms (1kHz)
static void mdlInitializeSampleTimes(SimStruct *S)
{
// 有关此处添加内容的示例,参见 https://techoverflow.net/2024/10/20/matlab-level-2-s-function-example-sine-wave-continous-output/
}
// Function: mdlOutputs =======================================================
// Abstract:
// 基于仿真时间计算正弦波输出。
static void mdlOutputs(SimStruct *S, int_T tid)
{
// 有关此处添加内容的示例,参见 https://techoverflow.net/2024/10/20/matlab-level-2-s-function-example-sine-wave-continous-output/
}
// Function: mdlTerminate =====================================================
// Abstract:
// 此函数在仿真结束时调用,用于清理。
static void mdlTerminate(SimStruct *S)
{
// 本示例无需清理
}
// 必需的 S-function trailer
#ifdef MATLAB_MEX_FILE
#include "simulink.c" // MEX-file interface mechanism
#else
#include "cg_sfun.h" // Code generation interface
#endif编译命令:
build_string_param_sfunc.sh
mex -g string_param_sfunc.cpp CXXFLAGS="-std=gnu++17 -fPIC"Check out similar posts by category:
MATLAB/Simulink, C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow