Main Content

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';

In your system's temporary folder, create a temporary folder for the build and inspection process.

currentDir = pwd;
[~,cgDir] = rtwdemodir();

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 Standard math library parameter to C++03 (ISO).

set_param(model, 'TargetLangStandard', 'C++03 (ISO)');

Build the 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(cgDir,'mStrfindSubStr_ert_rtw','mStrfindSubStr.h');
rtwdemodbtype(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(cgDir,'mStrfindSubStr_ert_rtw','mStrfindSubStr.cpp');
rtwdemodbtype(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.



An array of a bus that contains std:string is not supported in software-in-loop (SIL) and processor-in-loop (PIL) simulations.

Related Topics