Matlab/Simulink:如何将 S-function 参数提取为 std::string
此辅助函数允许你从 MATLAB/Simulink 中的 S-function 提取字符串参数并将其作为 std::string 返回。它处理参数可能未设置或不是字符串的情况,必要时返回默认值。
extract_sfunction_param.cpp
// 从 S-function 参数获取字符串参数的辅助函数
static std::string extractSFunctionParameterAsString(SimStruct *S, int paramIndex, const std::string& defaultValue = "default") {
const mxArray* param = ssGetSFcnParam(S, paramIndex);
if (param == nullptr || !mxIsChar(param)) {
return defaultValue; // 默认回退
}
// 获取字符串长度并分配缓冲区
mwSize nameLen = mxGetNumberOfElements(param) + 1;
char* nameBuffer = new char[nameLen];
// 从 MATLAB 参数中提取字符串
if (mxGetString(param, nameBuffer, nameLen) == 0) {
std::string result(nameBuffer);
delete[] nameBuffer;
return result;
} else {
delete[] nameBuffer;
return defaultValue;
}
}不要忘记在 mdlInitializeSizes() 中使用 ssSetNumSFcnParams() 设置 S-function 的参数数量,并在 Simulink 模型中定义参数:
sfunction_param_example.c
static void mdlInitializeSizes(SimStruct *S) {
ssSetNumSFcnParams(S, 1); // 设置参数数量
// 示例用法
std::string myParam = extractSFunctionParameterAsString(S, 0, "default_value");
// 根据需要使用 myParam
}Check out similar posts by category:
Matlab/Simulink
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow