MATLAB Examples

Integrate External C Code Into Generated Code By Using Custom Code Blocks and Model Configuration Parameters

This example shows how to place external code in generated code by using custom code blocks and model configuration parameters.

1. Open the model rtwdemo_slcustcode.


2. Open the Model Configuration Parameters dialog box and navigate to the Custom Code pane.

3. Examine the settings for parameters Source file and Initialize function.

  • Source file specifies a comment and sets the variable GLOBAL_INT2 to -1.
  • Initialize function initializes the variable GLOBAL_INT2 to 1.

4. Close the dialog box.

5. Double-click the Model Source block. The Top of Model Source field specifies that the code generator declare the variable GLOBAL_INT1 and set it to 0 at the top of the generated file rtwdemo_slcustcode.c.

6. Open the triggered subsystem Amplifier. The subsystem includes the System Outputs block. The code generator places code that you specify in that block in the generated code for the nearest parent atomic subsystem. In this case, the code generator places the external code in the generated code for the Amplifier subsystem. The external code:

  • Declares the pointer variable *intPtr and initializes it with the value of variable GLOBAL_INT1.
  • Sets the pointer variable to -1 during execution.
  • Resets the pointer variable to 0 before exiting.

7. Generate code and a code generation report.

8. Examine the code in the generated source file rtwdemo_slcustcode.c. At the top of the file, after the #include statements, you find the following declaration code. The example specifies the first declaration with the Source file configuration parameter and the second declaration with the Model Source block.

int_T GLOBAL_INT2 = -1;

int_T GLOBAL_INT1 = 0;

The Output function for the Amplifier subsystem includes the following code, which shows the external code integrated with generated code that applies the gain. The example specifies the three lines of code for the pointer variable with the System Outputs block in the Amplifier subsystem.

int_T *intPtr = &GLOBAL_INT1;

*intPtr = -1;

rtwdemo_slcustcode_Y.Output = rtwdemo_slcustcode_U.Input << 1;

*intPtr = 0;

The following assignment appears in the model initialize entry-point function. The example specifies this assignment with the Initialize function configuration parameter.