Generate Code for String Blocks by Using the Standard C++ String Library
Optimize generated code for Simulink® string blocks by using standard C++ library string functions and string objects. The C++ string library provides consistent C++ code and improves functionality, such as string length retrieval, concatenation, string copy, string swapping, string comparison, and substring computations.
Example Model
In the model matlab:mStrfindSubStr, a string constant block that has the value "Hello!" connects to the str
port of a String Find block. An inport connects to the sub
port of the same String Find block.
model = 'mStrfindSubStr';
open_system(model);
Generate Code by Using C++ String Libraries
In the Configuration Parameters dialog box, set the Language parameter to C++
.
set_param(model, 'TargetLang', 'C++');
In the Configuration Parameters dialog box, set the Code interface packaging parameter to C++ class
.
set_param(model, 'CodeInterfacePackaging', 'C++ class');
In the Configuration Parameters dialog box, set the Language standard parameter to C++03 (ISO)
.
set_param(model, 'TargetLangStandard', 'C++03 (ISO)');
Build the model.
evalc('slbuild(model)');
View the generated code with C++ string library objects. Here is a portion of mStrfindSubStr.h
. The code instantiates a std:string object In1
.
cfile = fullfile(pwd,'mStrfindSubStr_ert_rtw','mStrfindSubStr.h'); coder.example.extractLines(cfile,'External inputs','External outputs',0,0);
struct ExtU_mStrfindSubStr_T { std::string In1; // '<Root>/In1' };
View the generated code with C++ string library functions. Here is a portion of mStrfindSubStr.cpp
. The code uses the find
function to look for the first character match, which is present in the C++ string library.
cfile = fullfile(pwd,'mStrfindSubStr_ert_rtw','mStrfindSubStr.cpp'); coder.example.extractLines(cfile,'Model step function','Model initialize function',0,0);
void untitled1ModelClass::step() { uint32_T tmpOut; // StringFind: '<Root>/String Find' incorporates: // Inport: '<Root>/In1' // StringConstant: '<Root>/String Constant' tmpOut = mStrfindSubStr_P.StringConstant_String.find(mStrfindSubStr_U.In1); if (tmpOut == (uint32_T)std::string::npos) { // Outport: '<Root>/Out1' mStrfindSubStr_Y.Out1 = -1; } else { // Outport: '<Root>/Out1' mStrfindSubStr_Y.Out1 = static_cast<int32_T>(tmpOut) + 1; } // End of StringFind: '<Root>/String Find' }
This code executes faster and is easier to read. Close the model and the code generation report.
bdclose(model);
Limitations:
An array of a bus that contains std:string is not supported in software-in-the-loop (SIL) and processor-in-the-loop (PIL) simulations.