| Contents | Index |
Using the Language option, C++ (Encapsulated), on the Code Generation pane of the Configuration Parameters dialog box, you can generate a C++ class interface to model code. The generated interface encapsulates all required model data into C++ class attributes and all model entry point functions into C++ class methods. The benefits of encapsulation include:
Greater control over access to model data
Ability to multiply instantiate model classes
Easier integration of model code into C++ programming environments
C++ encapsulation also works for right-click builds of nonvirtual subsystems. (For information on requirements that apply, see Configuring C++ Encapsulation Interfaces for Nonvirtual Subsystems.)
The general procedure for generating C++ encapsulation interfaces to model code is as follows:
Configure your model to use an ert.tlc system target file provided by MathWorks.
Select the language option C++ (Encapsulated) for your model.
Optionally, configure related C++ encapsulation interface settings for your model code, using either a graphical user interface (GUI) or application programming interface (API).
Generate model code and examine the results.
To get started with an example, see C++ Encapsulation Quick-Start Example. For more details about configuring C++ encapsulation interfaces for your model code, see Generating and Configuring C++ Encapsulation Interfaces to Model Code and Configuring C++ Encapsulation Interfaces Programmatically. For limitations that apply, see C++ Encapsulation Interface Control Limitations.
Note For a demonstration of the C++ encapsulation capability, see the demo model rtwdemo_cppencap. |
This example illustrates a simple use of the C++ (Encapsulated) option. It uses C++ encapsulation to generate interfaces for code from a demo model, without extensive modifications to default settings.
Note For details about setting C++ encapsulation options, see the sections that follow this example, beginning with Generating and Configuring C++ Encapsulation Interfaces to Model Code. |
To generate C++ encapsulated interfaces for a Simulink model:
Open a model for which you would like to generate C++ encapsulation interfaces. This example uses the demo model rtwdemo_counter.
Configure the model to use an ert.tlc system target file provided by MathWorks. For example, open the Configuration Parameters dialog box, go to the Code Generation pane, select a target value from the System target file menu, and click Apply.
Optionally, as a baseline for later code comparison, generate code from the model using a different Language parameter setting, C++ or C. (You can set up the build directory naming or location to distinguish your baseline build from later builds of the same model.)
On the Code Generation pane of the Configuration Parameters dialog box, select the C++ (Encapsulated) language option.

Click Apply.
Go to the Interface pane of the Configuration Parameters dialog box and examine the Code interface subpane.

When you selected the C++ (Encapsulated) language option for your model, C++ encapsulation interface controls replaced the default options on the Code interface subpane. See Configuring Code Interface Options for descriptions of these controls. You might want to modify the default settings according to your application.
Click the Configure C++ Encapsulation Interface button. This action opens the Configure C++ encapsulation interface dialog box, which allows you to configure the step method for your generated model class. The dialog box initially displays a view for configuring a void-void style step method (passing no I/O arguments) for the model class. In this view, you can rename the model class and the step method for your model.

See Configuring the Step Method for Your Model Class for descriptions of these controls.
If you want root-level model input and output to be arguments on the step method, select the value I/O arguments step method from the Function specification menu. The dialog box displays a view for configuring an I/O arguments style step method for the model class.

See Configuring the Step Method for Your Model Class for descriptions of these controls.
Click the Get Default Configuration button. This action causes a Configure C++ encapsulation interface subpane to appear in the dialog box. The subpane displays the initial interface configuration for your model, which provides a starting point for further customization.

See Passing I/O Arguments for descriptions of these controls.
Perform this optional step only if you want to customize the configuration of the I/O arguments generated for your model step method.
If you choose to perform this step, first you must check that the required option Remove root level I/O zero initialization is selected on the Optimization pane, and then navigate back to the I/O arguments step method view of the Configure C++ encapsulation interface dialog box.
Now you can use the dialog box controls to configure I/O argument attributes. For example, in the Configure C++ encapsulation interface subpane, in the row for the Input argument, you can change the value of Category from Value to Pointer and change the value of Qualifier from none to const *. The preview updates to reflect your changes. Click the Validate button to validate the modified interface configuration.
Continue modifying and validating until you are satisfied with the step method configuration.

Click Apply and OK.
Generate code for the model. When the build completes, the code generation report for rtwdemo_counter appears. Examine the report and observe that all required model data is encapsulated into C++ class attributes and all model entry point functions are encapsulated into C++ class methods. For example, click the link for rtwdemo_counter.h to see the class declaration for the model.

Note
|
To select the C++ (Encapsulated) option, in the Configuration Parameters dialog box, on the Code Generation pane, use the Language menu:

When you select this option, you see the following effects on other panes in the Configuration Parameters dialog box:
Disables model configuration options that C++ (Encapsulated) does not support. For details, see C++ Encapsulation Interface Control Limitations.
Replaces the default options on the Interface pane, in the Code interface subpane, with C++ encapsulation interface controls, which are described in the next section.
When you select the C++ (Encapsulated) option for your model, the C++ encapsulation interface controls shown below replace the Code interface default options on the Interface pane.

Block parameter visibility
Specifies whether to generate the block parameter structure as a public, private, or protected data member of the C++ model class (private by default).
Internal data visibility
Specifies whether to generate internal data structures, such as Block I/O, DWork vectors, Runtime model, Zero-crossings, and continuous states, as public, private, or protected data members of the C++ model class (private by default).
Block parameter access
Specifies whether to generate access methods for block parameters for the C++ model class (None by default). You can select noninlined access methods (Method) or inlined access methods (Inlined method).
Internal data access
Specifies whether to generate access methods for internal data structures, such as Block I/O, DWork vectors, Runtime model, Zero-crossings, and continuous states, for the C++ model class (None by default). You can select noninlined access methods (Method) or inlined access methods (Inlined method).
External I/O access
Specifies whether to generate access methods for root-level I/O signals for the C++ model class (None by default). If you want to generate access methods, you have the following options:
Generate either noninlined or inlined access methods.
Generate either per-signal or structure-based access methods. That is, you can generate a series of set and get methods on a per-signal basis, or generate just one set method that takes the address of an external input structure as an argument and, for external outputs (if applicable), just one get method that returns a reference to an external output structure. The generated code for structure-based access methods has the following general form:
class ModelClass {
...
/* Root inports set method*/
void setExternalInputs(const ExternalInputs* pExternalInputs);
/* Root outports get method*/
const ExternalOutputs & getExternalOutputs() const;
}Note This parameter affects generated code only if you are using the default (void-void style) step method for your model class; not if you are explicitly passing arguments for root-level I/O signals using an I/O arguments style step method. For more information, see Passing No Arguments (void-void) and Passing I/O Arguments. |
Terminate function
Specifies whether to generate the model_terminate function (on by default). This function contains all model termination code and should be called as part of system shutdown.
Generate destructor
Specifies whether to generate a destructor for the C++ model class (on by default).
Use operator new for referenced model object registration
For a model containing Model blocks, specifies whether generated code should use dynamic memory allocation, during model object registration, to instantiate objects for referenced models configured with a C++ encapsulation interface (off by default). If you select this option, during instantiation of an object for the top model in a model reference hierarchy, the generated code uses the operator new to instantiate objects for referenced models.
Selecting this option frees a parent model from having to maintain information about submodels beyond its direct children. Clearing this option means that a parent model maintains information about all of its submodels, including its direct and indirect children.
Note If you select this option, be aware that a bad_alloc exception might be thrown, per the C++ standard, if an out-of-memory error occurs during the use of new. You must provide code to catch and process the bad_alloc exception in case an out-of-memory error occurs for a new call during construction of a top model object. |
Generate preprocessor conditionals
For a model containing Model blocks, specifies whether to generate preprocessor conditional directives globally for a model, locally for each variant Model block, or conditionally based on the Generate preprocessor conditionals setting in the Model Reference Parameter dialog for each variant Model block (Use local settings by default).
Suppress error status in real-time model data structure
Specifies whether to omit the error status field from the generated real-time model data structure rtModel (off by default). Selecting this option reduces memory usage.
Be aware that selecting this option can cause the code generator to omit the rtModel data structure from generated code.
Combine signal/state structures
Specifies whether to combine global block signals and global state data into one data structure in the generated code (off by default). Selecting this option reduces RAM and improves readability of the generated code.
Configure C++ Encapsulation Interface
Opens the Configure C++ encapsulation interface dialog box, which allows you to configure the step method for your model class. For more information, see Configuring the Step Method for Your Model Class.
To configure the step method for your model class, on the Interface pane, click the Configure C++ Encapsulation Interface button, which is available when you selectC++ (Encapsulated) for your model. This action opens the Configure C++ encapsulation interface dialog box, where you can configure the step method for your model class in either of two styles:
Note The void-void style of step method specification supports single-rate models and multirate models, while the I/O arguments style supports single-rate models and multirate single-tasking models. |
Passing No Arguments (void-void). The Configure C++ encapsulation interface dialog box initially displays a view for configuring a void-void style step method for the model class.

Step method name
Allows you to specify a step method name other than the default, step.
Class name
Allows you to specify a model class name other than the default, modelModelClass.
Step function preview
Displays a preview of the model step function prototype as currently configured. The preview display is dynamically updated as you make configuration changes.
Validate
Validates your current model step function configuration. The Validation pane displays success or failure status and an explanation of any failure.
Passing I/O Arguments. If you select I/O arguments step method from the Function specification menu, the dialog box displays a view for configuring an I/O arguments style step method for the model class.
Note To use the I/O arguments style step method, you must select the option Remove root level I/O zero initialization on the Optimization pane of the Configuration Parameters dialog box. |

Get Default Configuration
Click this button to get the initial interface configuration that provides a starting point for further customization.
Step function preview
Displays a preview of the model step function prototype as currently configured. The preview dynamically updates as you make configuration changes.
Validate
Validates your current model step function configuration. The Validation pane displays success or failure status and an explanation of any failure.
When you click Get Default Configuration, the Configure C++ encapsulation interface subpane appears in the dialog box, displaying the initial interface configuration. For example:

Step method name
Allows you to specify a step method name other than the default, step.
Class name
Allows you to specify a model class name other than the default, modelModelClass.
Order
Displays the numerical position of each argument. Use the Up and Down buttons to change argument order.
Port Name
Displays the port name of each argument (not configurable using this dialog box).
Port Type
Displays the port type, Inport or Outport, of each argument (not configurable using this dialog box).
Category
Displays the passing mechanism for each argument. To change the passing mechanism for an argument, select Value, Pointer, or Reference from the argument's Category menu.
Argument Name
Displays the name of each argument. To change an argument name, click in the argument's Argument name field, position the cursor for text entry, and enter the new name.
Qualifier
Displays the const type qualifier for each argument. To change the qualifier for an argument, select an available value from the argument's Qualifier menu. The possible values are:
none
const (value)
const* (value referenced by the pointer)
const*const (value referenced by the pointer and the pointer itself)
const & (value referenced by the reference)
Tip When a model includes a referenced model, the const type qualifier for the root input argument of the referenced model's specified step function interface is set to none and the qualifier for the source signal in the referenced model's parent is set to a value other than none, code generation honors the referenced model's interface specification by generating a type cast that discards the const type qualifier from the source signal. To override this behavior, add a const type qualifier to the referenced model. |
C++ encapsulation interfaces can be configured for right-click builds of nonvirtual subsystems in Simulink models, provided that:
You select the system target file ert.tlc for the model.
You select the Language parameter value C++ (Encapsulated) for the model.
The subsystem is convertible to a Model block using the function Simulink.SubSystem.convertToModelReference. For referenced model conversion requirements, see the Simulink reference page Simulink.SubSystem.convertToModelReference.
To configure C++ encapsulation interfaces for a subsystem that meets the requirements:
Open the containing model and select the subsystem block.
Enter the following MATLAB command:
RTW.configSubsystemBuild(gcb)
where gcb is the Simulink function gcb, returning the full block path name of the current block.
This command opens a subsystem equivalent of the Configure C++ encapsulation interface dialog sequence that is described in detail in the preceding section, Configuring the Step Method for Your Model Class. (For more information about using the MATLAB command, see RTW.configSubsystemBuild.)
Use the Configure C++ encapsulation interface dialog boxes to configure C++ encapsulation settings for the subsystem.
Right-click the subsystem and select Code Generation > Build Subsystem.
When the subsystem build completes, you can examine the C++ encapsulation interfaces in the generated files and the HTML code generation report.
If you select the Language option C++ (Encapsulated) for your model, you can use the C++ encapsulation interface control functions (listed in C++ Encapsulation Interface Control Functions) to programmatically configure the step method for your model class.
Typical uses of these functions include:
Create and validate a new step method interface, starting with default configuration information from your Simulink model
Create a model-specific C++ encapsulation interface with obj = RTW.ModelCPPVoidClass or obj = RTW.ModelCPPArgsClass, where obj returns a handle to an newly created, empty C++ encapsulation interface.
Attach the C++ encapsulation interface to your loaded ERT-based Simulink model using attachToModel.
Get default C++ encapsulation interface configuration information from your model using getDefaultConf.
Use the Get and Set functions listed in C++ Encapsulation Interface Control Functions to test or reset the model class name and model step method name. Additionally, if you are using the I/O arguments style step method, you can test and reset argument names, argument positions, argument categories, and argument type qualifiers.
Validate the C++ encapsulation interface using runValidation. (If validation fails, use the error message information thatrunValidation returns to address the issues.)
Save your model and then generate code using the rtwbuild function.
Modify and validate an existing step method interface for a Simulink model
Get the handle to an existing model-specific C++ encapsulation interface that is attached to your loaded ERT-based Simulink model using obj = RTW.getEncapsulationInterfaceSpecification(modelName), where modelName is a string specifying the name of a loaded ERT-based Simulink model, and obj returns a handle to a C++ encapsulation interface attached to the specified model. If the model does not have an attached C++ encapsulation interface configuration, the function returns [].
Use the Get and Set functions listed in C++ Encapsulation Interface Control Functions to test or reset the model class name and model step method name. Additionally, if the returned interface uses the I/O arguments style step method, you can test and reset argument names, argument positions, argument categories, and argument type qualifiers.
Validate the C++ encapsulation interface using runValidation. (If validation fails, use the error message information that runValidation returns to address the issues.)
Save your model and then generate code using the rtwbuild function.
Note You should not use the same model-specific C++ encapsulation interface control object across multiple models. If you do, changes that you make to the step method configuration in one model propagate to other models, which is usually not desirable. |
C++ Encapsulation Interface Control Functions
| Function | Description |
|---|---|
| attachToModel | Attach model-specific C++ encapsulation interface to loaded ERT-based Simulink model |
| getArgCategory | Get argument category for Simulink model port from model-specific C++ encapsulation interface |
| getArgName | Get argument name for Simulink model port from model-specific C++ encapsulation interface |
| getArgPosition | Get argument position for Simulink model port from model-specific C++ encapsulation interface |
| getArgQualifier | Get argument type qualifier for Simulink model port from model-specific C++ encapsulation interface |
| getClassName | Get class name from model-specific C++ encapsulation interface |
| getDefaultConf | Get default configuration information for model-specific C++ encapsulation interface from Simulink model to which it is attached |
| getNumArgs | Get number of step method arguments from model-specific C++ encapsulation interface |
| getStepMethodName | Get step method name from model-specific C++ encapsulation interface |
| RTW.configSubsystemBuild | Open GUI to configure C function prototype or C++ encapsulation interface for right-click build of specified subsystem |
| RTW.getEncapsulationInterfaceSpecification | Get handle to model-specific C++ encapsulation interface control object |
| runValidation | Validate model-specific C++ encapsulation interface against Simulink model to which it is attached |
| setArgCategory | Set argument category for Simulink model port in model-specific C++ encapsulation interface |
| setArgName | Set argument name for Simulink model port in model-specific C++ encapsulation interface |
| setArgPosition | Set argument position for Simulink model port in model-specific C++ encapsulation interface |
| setArgQualifier | Set argument type qualifier for Simulink model port in model-specific C++ encapsulation interface |
| setClassName | Set class name in model-specific C++ encapsulation interface |
| setStepMethodName | Set step method name in model-specific C++ encapsulation interface |
The following sample MATLAB script configures the step method for the rtwdemo_counter model class, using the C++ Encapsulation Interface Control Functions.
%% Open the rtwdemo_counter model
rtwdemo_counter
%% Select ert.tlc as the System Target File for the model
set_param(gcs,'SystemTargetFile','ert.tlc')
%% Select C++ (Encapsulated) as the target language for the model
set_param(gcs,'TargetLang','C++ (Encapsulated)')
%% Set required option for I/O arguments style step method (cmd off = GUI on)
set_param(gcs,'ZeroExternalMemoryAtStartup','off')
%% Create a C++ encapsulated interface using an I/O arguments style step method
a=RTW.ModelCPPArgsClass
%% Attach the C++ encapsulated interface to the model
attachToModel(a,gcs)
%% Get the default C++ encapsulation interface configuration from the model
getDefaultConf(a)
%% Move the Output port argument from position 2 to position 1
setArgPosition(a,'Output',1)
%% Reset the model step method name from step to StepMethod
setStepMethodName(a,'StepMethod')
%% Change the Input port argument name, category, and qualifier
setArgName(a,'Input','inputArg')
setArgCategory(a,'Input','Pointer')
setArgQualifier(a,'Input','const *')
%% Validate the function prototype against the model
[status,message]=runValidation(a)
%% if validation succeeded, generate code and build
if status
rtwbuild(gcs)
endThe C++ (Encapsulated) option does not support some Simulink model configuration options. Selecting C++ (Encapsulated) disables the following items in the Configuration Parameters dialog box:
Identifier format control subpane on the Symbols pane
Templates pane
The Templates pane parameter File customization template is not supported for C++ (Encapsulated) code generation.
Selecting C++ (Encapsulated) turns on the Templates pane option Generate an example main program but removes it from the Configuration Parameters dialog box. If desired, you can disable it using the command line parameter GenerateSampleERTMain.
Code Placement pane
Memory Sections pane
Among the data exchange interfaces available on the Interface pane of the Configuration Parameters dialog box, only the C API interface is supported for C++ (Encapsulated) code generation. If you select External mode or ASAP2, code generation fails with a validation error.
The I/O arguments style of step method specification supports single-rate models and multirate single-tasking models, but not multirate multitasking models.
The C++ (Encapsulated) option does not support use of the IncludeERTFirstTime model option to include the firstTime argument in the model_initialize function generated for an ERT-based models. (The IncludeERTFirstTime option is off by default except for models created with R2006a.) Also, the C++ (Encapsulated) option requires that the target selected for the model support firstTime argument control by setting the ERTFirstTimeCompliant target option, which all targets provided by MathWorks do by default. In other words, the C++ (Encapsulated) option requires that the target option ERTFirstTimeCompliant is on and the model option IncludeERTFirstTime is off.
The Code Generation > Export Functions capability does not support C++ (Encapsulated) as the target language.
For a Stateflow chart that resides in a root model configured to use the I/O arguments step method function specification, and that uses a model root inport value or calls a subsystem that uses a model root inport value, you must do one of the following to generate code:
Clear the Execute (enter) Chart At Initialization check box in the Stateflow chart.
Insert a Signal Conversion block immediately after the root inport and select the Exclude this block from 'Block reduction' optimization check box in the Signal Conversion block parameters.
When building a referenced model that is configured to generate a C++ encapsulation interface:
You must use the I/O arguments step method style of the C++ encapsulated interface. The void-void step method style is not supported for referenced models.
You cannot use a C++ encapsulation interface in cases when a referenced model cannot have a combined output/update function. Cases include a model that
Has multiple sample times
Has a continuous sample time
Saves states
![]() | Function Prototype Control | Atomic Subsystem Code | ![]() |

Learn more about Simulink through this collection of videos, articles, technical literature and the Getting Started with Simulink Guide.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |