Main Content

Configure Model to Generate C API Code for States

This example shows how to configure the model to include the C API for states in the generated code.

Open the model CapiConfigDemo.

capiMdl = "CapiConfigDemo";
open_system(capiMdl);

The two Unit Delay blocks, unitDelay1 and unitDelay2, contain states. To see which blocks have states, open the Code Mappings editor (see Open the Code Mappings Editor – C), select the Signals/States tab, and expand States.

Code Mappings editor. The Signals/States tab is open with the States group expended. The storage classes of the two Unit Delay block states are specified as Auto and Model default.

Alternatively, you can use the find function with the code mappings object of the model to see which blocks contain states.

codeMapObj = coder.mapping.api.get(capiMdl);
disp(string(get_param(find(codeMapObj,"States"),"Name")))
    "unitDelay2"
    "unitDelay1"

Enable C API Generation for States

To enable C API code generation for states:

  1. Open the Configuration Parameters dialog box.

  2. Navigate to Code Generation > Interface pane.

  3. In the Data exchange interface > Generate C API for section, select states.

  4. Click OK.

Configuration Parameters dialog box. The Code Generation > Interface pane is open. In the Generate C API for section, the states box is selected.

Alternatively, enter this in the Command Window:

set_param(capiMdl,RTWCAPIStates=true)

C API code generation is not dependent on the states storage classes. In this example, the C API code is generated for both model states, where the state in unitDelay1 is configured with storage class Auto and the state in unitDelay2 is configured with storage class Model default.

Generate Model Code

Use the slbuild command to generate code from your model. Use evalc to suppress the output of the slbuild command.

evalc("slbuild(capiMdl,GenerateCodeOnly=true)");

Verify That States Are Included in C API

The C API structure array that corresponds to model states is rtBlockStates. To view the instantiation code for this structure, examine the generated C API source file CapiConfigDemo_capi.c (located in the folder CapiConfigDemo_grt_rtw).

This is the instantiation code for the structure in this file:

/* Block states information */
static const rtwCAPI_States rtBlockStates[] = {
  /* addrMapIndex, contStateStartIndex, blockPath,
   * stateName, pathAlias, dWorkIndex, dataTypeIndex, dimIndex,
   * fixPtIdx, sTimeIndex, isContinuous, hierInfoIdx, flatElemIdx
   */
  { 0, -1, TARGET_STRING("CapiConfigDemo/unitDelay1"),
    TARGET_STRING("DSTATE"), "", 0, 0, 0, 0, 0, 0, -1, 0 },

  { 1, -1, TARGET_STRING("CapiConfigDemo/unitDelay2"),
    TARGET_STRING("DSTATE"), "", 0, 0, 0, 0, 0, 0, -1, 0 },

  {
    0, -1, (NULL), (NULL), (NULL), 0, 0, 0, 0, 0, 0, -1, 0
  }
};

Related Topics