Main Content

Include Custom C Code Functions and Structures

This model shows how Stateflow® allows you to incorporate and to call your custom-written C code functions.

In this particular example, a C function defined in my_function.c and a structure that is defined in my_header.h are included in the chart. MY_FUNCTION multiplies its input by two. The structure in my_header.h is defined as follows:

typedef struct { real_T a; int8_T b[10]; } MyStruct;

The model accesses the structure member using the dot notation MyStruct.a and also with the use of the pointer gMyStructPointerVar ->b[1].

Integrate C Code into Model

Custom written C-files can be integrated easily into Stateflow models. Custom code can be used to augment the capabilities of your Stateflow chart and to take advantage of legacy code.

To add custom C-files open the Model Configuration Parameters dialog box, select the Simulation Target pane, and enter:

  • Header file: Header that defines functions, structures, and data to be accessible by Stateflow.

  • Include directories: Path to folders that contain your custom code.

  • Source files: C-files that define the functions and data accessible by Stateflow.

If you are generating code through Simulink Coder, add the same settings to the Code Generation > Custom Code pane.

Call C Code from Stateflow

Functions: Stateflow charts call custom C-code functions by using the same syntax as graphical, truth table, MATLAB®, and Simulink® function calls:

result = my_custom_function(in_args);

Structures: Stateflow charts can access variables of structure type by using dot notation:

result = my_var.my_field;

Call C++ Code from Stateflow

Custom C++ code can also be integrated into Stateflow and Simulink Coder. For more information, see C++ Code Generation and Integration in Stateflow.

Related Topics