Skip to Main Content Skip to Search
Product Documentation

Custom Storage Classes

Introduction to Custom Storage Classes

During the build process, the storage class specification of a signal, tunable parameter, block state, or data object specifies how that entity is declared, stored, and represented in generated code. Note that in the context of the build process, the term "storage class" is not synonymous with the term "storage class specifier", as used in the C language.

The Simulink Coder software defines four built-in storage classes for use with all targets: Auto, ExportedGlobal, ImportedExtern, and ImportedExternPointer. These storage classes provide limited control over the form of the code generated for references to the data. For example, data of storage class Auto is typically declared and accessed as an element of a structure, while data of storage class ExportedGlobal is declared and accessed as unstructured global variables. For information about built-in storage classes, see Signals and Data, Function, and File Definition.

if the build-in storage classes do not provide data representation required by your application, you can define custom storage classes (CSCs). Embedded Coder (CSCs) extend the built-in storage classes provided by the Simulink Coder software. CSCs can provide application-specific control over the constructs required to represent data in an embedded algorithm. For example, you can use CSCs to:

Custom storage classes affect only code generated for ERT targets. When Configuration Parameters > Code Generation > Target Selection > System target file specifies a GRT target, the names of custom storage classes sometimes appear in dialog boxes, but selecting a CSC is functionally the same as selecting Auto. See Targets and Code Formats for information about ERT and GRT targets.

Custom Storage Class Memory Sections

Every custom storage class has an associated memory section definition. A memory section is a named collection of properties related to placement of an object in memory; for example, in RAM, ROM, or flash memory. Memory section properties let you specify storage directives for data objects. For example, you can specify const declarations, or compiler-specific #pragma statements for allocation of storage in ROM or flash memory sections.

See Creating and Editing Memory Section Definitions for details about using the Custom Storage Class designer to define memory sections. While memory sections are often used with data in custom storage classes, they can also be used with various other constructs. See Memory Sections for more information about using memory sections with custom storage classes, and complete information about using memory sections with other constructs.

Registering Custom Storage Classes

CSCs are associated with Simulink data class packages (such as the Simulink package) and with classes within packages (such as the Simulink.Parameter and Simulink.Signal classes). The custom storage classes associated with a package are defined by a CSC registration file. For example, a CSC registration file exists for the Simulink package. This registration file provides predefined CSCs for use with the Simulink.Signal and Simulink.Parameter classes, and with subclasses derived from these classes. The predefined CSCs are used for a wide variety of applications.

If you use only predefined CSCs, you do not need to be concerned with CSC registration files. You cannot add or change CSCs associated with built-in packages and classes, but you can create your own packages and subclasses, then associate CSCs with those. See Custom Storage Class Implementation for more information.

Custom Storage Class Demos

Three demos are available that show Custom Storage Class capabilities:

rtwdemo_cscpredef — Shows predefined custom storage classes and embedded signal objects

rtwdemo_importstruct — Shows custom storage classes used to access imported data efficiently

rtwdemo_advsc — Shows how custom storage classes can support data dictionary driven modeling

To launch a demo, click the demo's name above, or type its name in the MATLAB Command Window.

Resources for Defining Custom Storage Classes

The resources for working with custom storage class definitions are:

Simulink Package Custom Storage Classes

The Simulink package includes a set of built-in custom storage classes. These are categorized as custom storage classes, even though they are built-in, because they:

You cannot change the CSCs built into the Simulink package, but you can subclass the package and add CSCs to the subclass, following the steps in Resources for Defining Custom Storage Classes.

Some CSCs in the Simulink package are valid for parameter objects but not signal objects and vice versa. For example, you can assign the storage class Const to a parameter but not to a signal, because signal data is not constant. The next table defines the CSCs built into the Simulink package and shows where each of the CSCs can be used.

CSC NamePurposeSignals?Parameters?

BitField

Generate a struct declaration that embeds Boolean data in named bit fields.

Y

Y

CompilerFlagSupports preprocessor conditionals defined via compiler flag. See Variant Systems. NY

Const

Generate a constant declaration with the const type qualifier.

N

Y

ConstVolatile

Generate declaration of volatile constant with the const volatile type qualifier.

N

Y

Default

Default is a placeholder CSC that the code generator assigns to the RTWInfo.CustomStorageClass property of signal and parameter objects when they are created. You cannot edit the Default CSC definition.

Y

Y

Define

Generate #define directive.

N

Y

ExportToFile

Generate header (.h) file, with user-specified name, containing global variable declarations.

Y

Y

GetSetSupports specialized function calls to read and write the memory associated with a Data Store Memory block. See GetSet Custom Storage Class for Data Store Memory.YY
ImportedDefineSupports preprocessor conditionals defined via legacy header file. See Variant Systems.NY

ImportFromFile

Generate directives to include predefined header files containing global variable declarations.

Y

Y

Struct

Generate a struct declaration encapsulating parameter or signal object data.

Y

Y

Volatile

Use volatile type qualifier in declaration.

Y

Y

Creating Packages that Support CSC Definitions

You can create a package and associate your own CSC definitions with classes contained in the package. You do this by creating a data object package containing classes derived from Simulink.Parameter or Simulink.Signal. The procedure below shows how to create and configure such a package. For additional information, see Subclassing Simulink Data Classes.

  1. Open the Simulink Data Class Designer by choosing Tools > Data Class Designer in the model window, or typing the following at the MATLAB command prompt:

    sldataclassdesigner
  2. The Data Class Designer loads all packages that exist on the MATLAB path.

  3. To create a new package, click New next to the Package name field. If desired, edit the Package name. Then, click OK.

  4. In the Parent directory field, enter the path to the directory where you want to store the new package.

      Note   Do not create class package directories under matlabroot. Packages in these directories are treated as built-in and will not be visible in the Data Class Designer.

  5. Click on the Classes tab.

  6. Create a new class by clicking New next to the Class name field. If desired, edit the Class name. Then, click OK.

  7. In the Derived from menus, select Simulink.Signal or Simulink.Parameter.

  8. The Create your own custom storage classes for this class option is now enabled. This option is enabled when the selected class is derived from Simulink.Signal or Simulink.Parameter. You must select this option to create CSCs for the new class. If the Create your own custom storage classes for this class option is not selected, the new class inherits the CSCs of the parent class.

      Note   To create a CSC registration file for a package, the Create your own custom storage classes for this class option must be selected for at least one of the classes in the package.

    In the figure below, a new package called mypkg has been created. This package contains a new class, derived from Simulink.Signal, called sig. The Create your own custom storage classes for this class option is selected.

    Complete instructions for using the Data Class Designer appear in Subclassing Simulink Data Classes in the Simulink documentation. See also the instructions that appear when you click the Custom Storage Classes tab.

  9. If desired, repeat steps 6–8 to add other derived classes to the package and associate CSCs with them.

  10. Click Confirm Changes. In the Confirm Changes pane, select the package you created. Add the parent directory to the MATLAB path if it is not already added. Then, click Write Selected.

    The package directories and files, including the CSC registration file, are written out to the parent directory.

  11. Click Close.

  12. You can now view and edit the CSCs belonging to your package in the Custom Storage Class Designer, which you open with the MATLAB command cscdesigner. Initially, the package contains only the Default CSC definition, as shown in the figure below.

  13. Add and edit your CSC and memory section definitions, as described in Designing Custom Storage Classes and Memory Sections. After you have created CSC definitions for your package, you can instantiate objects of the classes belonging to your package, and assign CSCs to them.

    You need to restart your MATLAB session before you can use the new CSCs with objects of your new classes.

Designing Custom Storage Classes and Memory Sections

Using the Custom Storage Class Designer

The Custom Storage Class Designer (cscdesigner) is a tool for creating and managing custom storage classes and memory sections. You can use the Custom Storage Class Designer to:

To open the Custom Storage Class Designer, type the following command at the MATLAB prompt:

cscdesigner

When first opened, the Custom Storage Class Designer scans all data class packages on the MATLAB path to detect packages that have a CSC registration file. A message is displayed while scanning proceeds. When the scan is complete, the Custom Storage Class Designer window appears:

The Custom Storage Class Designer window is divided into several panels:

Selecting a Data Class Package.  A CSC or memory section definition or reference is uniquely associated with a Simulink data class package. The link between the definition/reference and the package is formed when a CSC registration file (csc_registration.m) is located in the package directory.

You never need to search for or edit a CSC registration file directly: the Custom Storage Class Designer locates all available CSC registration files. The Select package menu contains names of all data class packages that have a CSC registration file on the MATLAB search path. At least one such package, the Simulink package, is always present.

When you select a package, the CSCs and memory section definitions belonging to the package are loaded into memory and their names are displayed in the scrolling list in the Custom storage class panel. The name and location of the CSC registration file for the package is displayed in the Filename panel.

If you select a user-defined package, by default you can use the Custom Storage Class Designer to edit its custom storage classes and memory sections. If you select a built-in package, you cannot edit its custom storage classes or memory sections. See Custom Storage Class Implementation for more information.

Selecting and Editing CSCs, Memory Sections, and References.  The Custom Storage Class / Memory Section panel lets you select, view, and (if the CSC is writable) edit CSC and memory section definitions and references. In the next figure and the subsequent examples, the selected package is mypkg. Instructions for creating a user-defined package like mypkg appear in Creating Packages that Support CSC Definitions.

The list at the top of the panel displays the definitions/references for the currently selected package. To select a definition/reference for viewing and editing, click on the desired list entry. The properties of the selected definition/reference appear in the area below the list. The number and type of properties vary for different types of CSC and memory section definitions. See:

The buttons to the right of the list perform these functions, which are common to both custom storage classes and memory definitions:

For example, if you click New, a new custom storage class is created with a default name:

You can now rename the new class by typing the desired name into the Name field, and specify any other fields. The changes take effect when you click Apply or OK. For example, you could set values for the new custom storage class as follows:

Saving Your Definitions.  After you have created or edited a CSC or memory section definition or reference, you must save the changes to the CSC registration file. To do this, click Save in the Filename panel. When you click Save, the current CSC and memory section definitions that are in memory are validated, and the definitions are written out.

If errors occur, they are reported in the Validation result panel. The definitions are saved whether or not errors exist. However, you should resolve any validation errors and resave your definitions. Trying to use definitions that were saved with validation errors can cause additional errors. Such problems can occur even it you do not try to use the specific parts of the definition that contain the validation errors, making the problems difficult to diagnose.

Restarting MATLAB After Changing Definitions.  If you add, change, or delete custom storage class or memory section definitions for any user-defined class, and objects of that class already exist, you must restart MATLAB to put the changed definitions into effect and eliminate obsolete objects. A message warning you to restart MATLAB appears when you save the changed definitions. This warning message does not affect the success of the save operation itself.

Editing Custom Storage Class Properties

To view and edit the properties of a CSC, click the Custom Storage Class tab in the Custom Storage Class / Memory Section panel. Then, select a CSC name from the Custom storage class definitions list.

The CSC properties are divided into several categories, selected by tabs. Selecting a class, and setting property values for that class, can change the available tabs, properties, and values. As you change property values, the effect on the generated code is immediately displayed in the Pseudocode preview panel. In most cases, you can define your CSCs quickly and easily by selecting the Pseudocode preview panel and using the Validate button frequently.

The property categories and corresponding tabs are as follows:

General.  Properties in the General category are common to all CSCs. In the next figure and the subsequent examples, the selected custom storage class is ByteField. Instructions for creating a user-defined custom storage class like ByteField appear in Selecting and Editing CSCs, Memory Sections, and References.

Properties in the General category, and the possible values for each property, are as follows:

.  

Structure Attributes.  The Structure Attributes panel gives you detailed control over code generation for structs (including bitfields). The Structure Attributes tab is displayed for CSCs whose Type parameter is set to FlatStructure. The following figure shows the Structure Attributes panel.

Structure Attributes Panel

The Structure Attributes properties are as follows:

The following listing is the pseudocode preview corresponding to the Structure Attributes properties displayed in.

Header file:

No header file is specified. By default, data is
exported with the generated model.h file.


Type definition:

/* CSC type comment generated by default */

typedef struct aToken myTag {
   :
} myType;


Declaration:

/* CSC declaration comment generated by default */

extern myType MyStruct;


Definition:

/* CSC definition comment generated by default */

myType MyStruct = {...};

Validating CSC Definitions.  To validate a CSC definition, select the definition on the Custom Storage Class panel and click Validate. The Custom Storage Class Designer then checks the definition for consistency. The Validation result panel displays any errors encountered when the selected CSC definition is validated. The next figure shows the Validation result panel with a typical error message:

Validation is also performed whenever CSC definitions are saved. In this case, all CSC definitions are validated. (See Saving Your Definitions.)

Using Custom Storage Class References

Any package can access and use custom storage classes that are defined in any other package, including both user-defined packages and predefined packages such as Simulink and mpt. Only one copy of the storage class exists, in the package that first defined it. Other packages refer to it by pointing to it in its original location. Thus any changes to the class, including changes to a predefined class in later MathWorks product releases, are immediately available in every referencing package.

To configure a package to use a custom storage class that is defined in another package:

  1. Type cscdesigner to launch the Custom Storage Class Designer. The relevant part of the designer window initially looks like this:

  2. Select the Custom Storage Class tab.

  3. Use Select Package to select the package in which you want to reference a class or section defined in some other package. The selected package must be writable.

  4. In the Custom storage class definitions pane, select the existing definition below which you want to insert the reference. For example:

  5. Click New Reference.

    A new reference with a default name and properties appears below the previously selected definition. The new reference is selected, and a Reference tab appears that shows the reference's initial properties. A typical appearance is:

  6. Use the Name field to enter a name for the new reference. The name must be unique in the importing package, but can duplicate the name in the source package. The name cannot be any TLC keyword. Violating this rule causes an error.

  7. Set Refer to custom storage class in package to specify the package that contains the custom storage class you want to reference.

  8. Set Custom storage class to reference to specify the custom storage class to be referenced. Trying to create a circular reference generates an error and leaves the package unchanged.

  9. Click OK or Apply to save the changes to memory. See Saving Your Definitions for information about saving changes permanently.

For example, the next figure shows the custom storage class ConstVolatile imported from the Simulink package into mypkg, and given the same name that it has in the source package. Any other name could have been used without affecting the properties of the storage class.

You can use Custom Storage Class Designer capabilities to copy, reorder, validate, and otherwise manage classes that have been added to a class by reference. However, you cannot change the underlying definitions. You can change a custom storage class only in the package where it was originally defined.

Changing Existing CSC References.  To change an existing CSC reference, select it in the Custom storage class definitions pane. The Reference tab appears, showing the current properties of the reference. Make any changes, then click OK or Apply to save the changes to memory. See Saving Your Definitions for information about saving changes permanently.

Creating and Editing Memory Section Definitions

Memory section definitions add comments, qualifiers, and #pragma directives to generated symbol declarations. The Memory Section tab lets you create, view, edit, and verify memory section definitions. The steps for creating a memory section definition are essentially the same as for creating a custom storage class definition:

  1. Select a writable package in the Select package field.

  2. Select the Memory Section tab. In a new package, only a Default memory section initially appears.

  3. Select the existing memory section below which you want to create a new memory section.

  4. Click New.

    A new memory section definition with a default name appears below the selected memory section.

  5. Set the name and other properties of the memory section.

  6. Click OK or Apply.

The next figure shows mypkg with a memory section called MyMemSect:

The Memory section definitions list lets you select a memory section definition to view or edit. The available memory section definitions also appear in the Memory section name menu in the Custom Storage Class panel. The properties of a memory section definition are as follows:

Previewing Generated Code.  If you click Validate on the Memory Section panel, the Pseudocode preview panel displays a preview of code that is generated from objects of the given class. The panel also displays messages (in blue) to highlight changes as they are made. The code preview changes dynamically as you edit the class properties. The next figure shows a code preview for the MemConstVolatile memory section.

Using Memory Section References

Any package can access and use memory sections that are defined in any other package, including both user-defined packages and predefined packages such as Simulink and mpt. Only one copy of the section exists, in the package that first defined it; other packages refer to it by pointing to it in its original location. Thus any changes to the section, including changes to a predefined section in later MathWorks product releases, are immediately available in every referencing package.

To configure a package to use a memory section that is defined in another package:

  1. Type cscdesigner to launch the Custom Storage Class Designer.

  2. Select the Memory Section tab.

  3. Use Select Package to select the package in which you want to reference a class or section defined in some other package.

  4. In the Memory section definitions pane, select the existing definition below which you want to insert the reference.

  5. Click New Reference.

    A new reference with a default name and properties appears below the previously selected definition. The new reference is selected, and a Reference tab appears that shows the reference's initial properties.

  6. Use the Name field to enter a name for the new reference. The name must be unique in the importing package, but can duplicate the name in the source package.

  7. Set Refer to memory section in package to specify the package that contains the memory section you want to reference.

  8. Set Memory section to reference to specify the memory section to be referenced. Trying to create a circular reference generates an error and leaves the package unchanged.

  9. Click OK or Apply to save the changes to memory. See Saving Your Definitions for information about saving changes permanently.

For example, the next figure shows the memory section MemConstVolatile imported from the Simulink package into mypkg, and given the same name that it has in the source package. Any other name could have been used without affecting the properties of the memory section.

You can use Custom Storage Class Designer capabilities to copy, reorder, validate, and otherwise manage memory sections that have been added to a class by reference. However, you cannot change the underlying definitions. You can change a memory section only in the package where it was originally defined.

Changing Existing Memory Section References.  To change an existing memory section reference, select it in the Memory section definitions pane. The Reference tab appears, showing the current properties of the reference. Make any changes, then click OK or Apply to save the changes to memory. See Saving Your Definitions for information about saving changes permanently.

Applying CSCs to Parameters and Signals

About Applying Custom Storage Classes

You can apply a custom storage class to a parameter or a signal using the GUI or the API.

Most of the GUI techniques, and most of the API techniques, are the same for parameter and signal objects, and for base workspace and embedded signal objects. Only the initial steps differ, after which you apply the same GUI or API instructions within the context that you established in the initial steps.

The following instructions assume that you have already created packages, custom storage classes, and memory sections, as described in Creating Packages that Support CSC Definitions and Designing Custom Storage Classes and Memory Sections.

Applying a Custom Storage Class to a Parameter

To apply a custom storage class to a parameter, you specify the storage class in the Simulink.Parameter object that defines the parameter in the base workspace. The instructions that begin in this section show you how to create that object using the GUI or API. Later instructions show you how to specify a custom storage class and custom attributes.

For information about using parameter objects to specify block parameter values, see Working with Block Parameters in the Simulink documentation. For information about parameter storage in generated code, see Parameters.

Providing a Parameter Object Using the GUI.  

  1. In the Model window, choose View > Model Explorer.

  2. In the Model Hierarchy pane, select the Base Workspace.

  3. Click the Add Parameter tool or choose Add > Simulink Parameter.

    Simulink creates a Simulink.Parameter object in the base workspace with the default name, Param.

  4. Change the parameter name by editing it in the Contents pane. Example: MyParam.

  5. Set parameter attributes other than Code generation options in the Dialog pane.

  6. Follow the instructions in Specifying a Custom Storage Class Using the GUI.

Providing a Parameter Object Using the API.  

  1. In the MATLAB Command Window, enter:

    ParamName=ParamClass

    where ParamClass is Simulink.Parameter or any subclass of it that you have defined.

  2. Simulink creates a ParamClass object with the specified name:

    MyParam =
     
    Simulink.Parameter (handle)
              Value: []
            RTWInfo: [1x1 Simulink.ParamRTWInfo]
        Description: ''
           DataType: 'auto'
                Min: []
                Max: []
           DocUnits: ''
         Complexity: 'real'
         Dimensions: [0 0]
  3. Set parameter attributes other than RTWInfo, which controls custom storage classes.

  4. Follow the instructions in Specifying a Custom Storage Class Using the API.

Applying a Custom Storage Class to a Signal

To apply a custom storage class to a signal, you specify the storage class in a Simulink.Signal object. This object can exist in either of two locations:

The object itself is the same in either case; only its location and some of the techniques for managing it differ. The instructions that begin in this section show you how to create a signal object in either location using the GUI or API. Later instructions show you how to specify the custom storage class and custom attributes.

A given signal can be associated with at most one signal object under any circumstances. The signal can refer to the object more that once, but every reference must resolve to exactly the same object. A different signal object that has exactly the same properties will not meet the requirement for uniqueness. A compile-time error occurs if a model associates more than one signal object with any signal.

Assigning a signal to any non-Auto storage class automatically makes the signal a test point, overriding the setting of Signal Properties > Logging and accessibility > Test point. See Working with Test Pointsfor more information.

For information about using signal objects to specify signal attributes, see Working with Signals in the Simulink documentation. For information about signal storage in generated code, see Signals.

Applying a CSC Using a Base Workspace Signal Object

The first step is to create the signal object in the base workspace, after which you specify any signal attributes and the custom storage class and attributes.

Providing a Base Workspace Signal Object Using the GUI.  

  1. In the Model window, choose View > Model Explorer.

  2. In the Model Hierarchy pane, select the Base Workspace.

  3. Click the Add Signal tool or choose Add > Simulink Signal.

    Simulink creates a Simulink.Signal object in the base workspace, with a default name, Sig.

  4. Change the signal name by editing it in the Contents pane. Example: MySig.

  5. Set signal attributes other than Code generation options in the Dialog pane.

  6. Give the signal the same name as the signal object, as described in About Signal Names.

  7. Arrange for the signal to resolve to the object, as described in Resolving Symbols.

  8. Follow the instructions in Specifying a Custom Storage Class Using the GUI.

Providing a Base Workspace Signal Object Using the API.  

  1. In the MATLAB Command Window, enter:

    SignalName=SignalClass

    where SignalClass is Simulink.Signal or any subclass of it that you have defined.

  2. Simulink creates a SignalClass object with the specified name:

    MySig =
     
    Simulink.Signal (handle)
             RTWInfo: [1x1 Simulink.SignalRTWInfo]
         Description: ''
            DataType: 'auto'
                 Min: []
                 Max: []
            DocUnits: ''
          Dimensions: -1
          Complexity: 'auto'
          SampleTime: -1
        SamplingMode: 'auto'
        InitialValue: ''
  3. Set parameter attributes other than RTWInfo, which controls custom storage classes.

  4. Give the signal the same name as the signal object, as described in About Signal Names.

  5. Arrange for the signal to resolve to the object, as described in Resolving Symbols.

  6. Follow the instructions in Specifying a Custom Storage Class Using the API.

Applying a CSC Using an Embedded Signal Object

You can use the GUI or the API to apply a CSC using an embedded signal object.

In either case, the effect on code generation is the same as if you had created a base workspace signal object that specified the same name, CSC, and custom attributes as the embedded signal object. See Applying a CSC Using a Base Workspace Signal Object for details.

The advantages of using embedded signal objects are that they do not clutter the base workspace, and they do not need to be saved separately from the model, as base workspace objects do. When you save a model, Simulink saves any embedded signal objects in the model file, and reloads the objects when you later reload the model.

The disadvantage of embedded signal objects is that you can use such an object only to specify a custom storage class, custom attributes, and an alias; you must accept the default values for all other signal attributes. You cannot work around this restriction by providing additional information in a base workspace signal object on the same signal, because a signal object can have at most one associated signal object, as described in Multiple Signal Objects.

Providing an Embedded Signal Object using the GUI.  

  1. Give the signal a name, which must be a valid ANSI C identifier. Example: MySig.

  2. Right-click the signal and choose Signal Properties from the context menu.

    The Signal Properties dialog box opens:

  3. Do not select Signal name must resolve to Simulink signal object. Selecting it would require a base workspace signal object, which would conflict with the embedded signal object.

  4. Click the Code Generation tab.

  5. The Package is initially ---None---. When no package is specified, only the non-custom built-in storage classes defined for both GRT and ERT targets are available:

    Applying a storage class when the package is ---None--- sets internal storage class attributes rather than creating an embedded signal object. For more information, see Signals and Data, Function, and File Definition.

  6. To apply a custom storage class, you must first specify the package where it is defined. Initially, viewing the Package menu displays only the built-in Simulink and mpt packages:

  7. Click Refresh to load any other available packages, including user-defined packages, available on the MATLAB path. After a brief delay, a timer box tracks the progress of the package search. After the search completes, viewing the Package menu displays all available packages:

    Once you have used Refresh in any Signal Properties dialog, Simulink saves the information for later use, so you do not have to click Refresh again during the current MATLAB session.

  8. Select the package that contains the custom storage class you want to apply, e.g. Simulink:

  9. Follow the instructions in Specifying a Custom Storage Class Using the GUI.

Deleting an Embedded Signal Object Using the GUI.  To delete an embedded signal object with the GUI, delete the name of the signal to which the object applies, by editing the name in the graphical model or in the Signal Properties dialog box. Simulink automatically deletes the embedded signal object as soon as its signal has no name.

Providing an Embedded Signal Object using the API.  To provide an embedded signal object using the API, you create the object, set its custom storage class and any custom attributes, then assign the object to the output port on which it will be embedded.

  1. Name the signal if it does not already have a name. The name must be a valid ANSI C identifier.

  2. In the MATLAB Command Window, enter:

    SignalName=SignalClass

    where SignalClass is Simulink.Signal or any subclass of it that you have defined. The name of the signal object does not need to match the name of the signal to which the object will be applied.

  3. Simulink creates a SignalClass object with the specified name. Example:

    MySig =
     
    Simulink.Signal (handle)
             RTWInfo: [1x1 Simulink.SignalRTWInfo]
         Description: ''
            DataType: 'auto'
                 Min: []
                 Max: []
            DocUnits: ''
          Dimensions: -1
          Complexity: 'auto'
          SampleTime: -1
        SamplingMode: 'auto'
        InitialValue: ''
  4. Do not set any attributes. An embedded signal object can specify only custom storage class information.

  5. Follow the instructions in Specifying a Custom Storage Class Using the API. After specifying the custom storage class, be sure to assign the signal object to its output port, as described under Assigning an Embedded Signal Object to an Output Port.

Changing an Embedded Signal Object Using the API.  To change an embedded signal object using the API, you obtain a copy of the object from the output port on which it is embedded, change the object, then assign the changed object back to the port.

  1. Obtain a copy of the signal object using a handle to the output port. Example:

    hps=get_param(gcb,'PortHandles')
    hp=hps.Outport(1)
    MySig=get_param(hp,'SignalObject')
  2. Change the signal object using the techniques described in Specifying a Custom Storage Class Using the API. After making the changes, be sure to copy the signal object to its output port, as described in Assigning an Embedded Signal Object to an Output Port.

Deleting an Embedded Signal Object Using the API.  To delete an embedded signal object with the API, obtain a handle to the output port where the signal object is embedded, then set the port's SignalObject parameter to []:

hps=get_param(gcb,'PortHandles')
hp=hps.Outport(1)
set_param(hp,'SignalObject',[])

Resolving a Signal Name to a Simulink Signal Object Using the API.  To set the name of a signal to resolve to a Simulink signal object using the API, obtain the handle to the output port and then set the port's MustResolveToSignalObject property to on:

hps=get_param(gcb,'PortHandles')
hp=hps.Outport(1)
set_param(hp,'MustResolveToSignalObject', 'on')

Specifying a Custom Storage Class Using the GUI

The initial steps for applying a CSC with the GUI differ depending on whether you are applying the CSC to a parameter using a base workspace object, to a signal using a base workspace object, or to a signal using an embedded object. The initial steps for each of these three cases appear in:

After the initial steps, applying a CSC with the GUI is the same in all three cases. The following instructions show you how to finish applying a CSC with the GUI. The instructions assume that you have completed one of the previous sets of instructions, and that the dialog you used to execute those instructions is still open.

The instructions given in this section apply to all packages, but the available custom storage classes and custom attributes depend on the package that you select. The examples in this section assume that you are using the Simulink package.

The dialog that you used to begin the process of applying a CSC with the GUI by providing an object contains two fields: one for specifying a custom storage class and one for optionally specifying an alias. These fields are the same in all three of the dialogs that you might use:

Storage class is Auto because that is the default storage class in the Simulink package. Other packages may have different defaults. You can specify an Alias whenever the Storage class is not Auto. If Storage class is Auto, Simulink deletes any alias you try to specify, leaving the field blank. If you specify an alias, it appears in generated code instead of the name of the object.

To specify a custom storage class and its custom attributes:

  1. View the Storage Class menu, which looks like this for the Simulink package:

    Each custom storage class has (custom) suffixed to its name. The storage classes SimulinkGlobal, ExportedGlobal, ImportedExtern, and ImportedExternPointer are the built-in non-custom storage classes described in Signals and Data, Function, and File Definition.

  2. Choose the desired custom storage class from Storage class, for example, Struct.

    If the storage class defines any custom attributes, fields for defining them appear:

  3. Provide values for any custom attributes. Struct has only one, Struct name. For example, set Struct name to MyStruct:

  4. Click Apply.

In generated code, all data whose storage is controlled by this custom storage class specification will appear in a structure named MyStruct. See Generating Code with Custom Storage Classes for an example.

Specifying a Custom Storage Class Using the API

The initial steps for applying a CSC with the API differ depending on whether you are applying the CSC to a parameter using a base workspace object, to a signal using a base workspace object, or to a signal using an embedded object. The initial steps for each of these three cases appear in:

After the initial steps, applying a CSC with the API is the same in all three cases, except for the case of an assignment for an embedded signal object. The following instructions show you how to finish applying a CSC with the API. The instructions assume that you have completed one of the previous sets of instructions, and that the resulting objects an attributes are unchanged.

The instructions given in this section apply to all packages, but the available custom storage classes and custom attributes depend on the package that you select. The examples in this section assume that you are using the Simulink package. The examples also assume that the object for which you want to specify a custom storage class is named MyObj, which is a parameter or signal object that exists in the base workspace, or a signal object that will be assigned to an output port.

The rest of this section provides information that is specific to custom storage classes in Embedded Coder. See Simulink Package Custom Storage Classes for a list of the custom storage classes that are built into the Simulink package for use by Embedded Coder software.

RTWInfo Properties.  Each Simulink parameter object or signal object defines properties called RTWInfo properties. Code generation software uses these properties to control storage class assignment in the generated code. The RTWInfo properties and their default values are:

          StorageClass: 'Auto'
                 Alias: ''
    CustomStorageClass: 'Default'
      CustomAttributes: [1x1 SimulinkCSC.AttribClass_Simulink_Default]

For more information about RTWInfo properties, see Signals and Data, Function, and File Definition.

Specifying a Custom Storage Class.  To specify a custom storage class using RTWInfo properties:

  1. Set StorageClass to 'Custom'.

  2. Set CustomStorageClass to the name of the storage class.

For example, to specify the Struct custom storage class:

MyObj.RTWInfo.StorageClass='Custom'
MyObj.RTWInfo.CustomStorageClass='Struct'

Whenever you have specified a custom storage class other than Auto, you can specify an alias by setting the Alias attribute. If you specify an alias, it appears in generated code instead of the name of the object.

Specifying Instance-Specific Attributes.  A custom storage class can have properties that define attributes that are specific to that CSC. Such properties are called instance-specific attributes. For example, if you specify the Struct custom storage class, you must specify the name of the C language structure that will store the data. That name is an instance-specific attribute of the Struct CSC.

Instance-specific attributes are stored in the RTWInfo property CustomAttributes. This property is initially defined as follows:

SimulinkCSC.AttribClass_Simulink_Default
1x1 struct array with no fields

When you specify a custom storage class, Simulink automatically populates RTWInfo.CustomAttributes with fields to represent any instance-specific attributes of that CSC. For example, if you set the MySig CSC to Struct, as described in Specifying a Custom Storage Class, then enter:

MyObj.RTWInfo.CustomAttributes

MATLAB displays:

SimulinkCSC.AttribClass_Simulink_Struct
    StructName: ''

To specify that StructName is MyStruct, enter:

MyObj.RTWInfo.CustomAttributes.StructName='MyStruct'

MATLAB displays:

SimulinkCSC.AttribClass_Simulink_Struct
    StructName: 'MyStruct'

Simulink Package CSC Instance-Specific Properties

Class NameInstance-Specific PropertyPurpose
BitFieldCustomAttributes.StructNameName of the bitfield struct into which the code generator packs the object's Boolean data.
ExportToFileCustomAttributes.HeaderFileName of header (.h) file that contains exported variable declarations and export directives for the object.
GetSetCustomAttributes.HeaderFileName of header (.h) file to #include in the generated code. See GetSet Custom Storage Class for Data Store Memory.
CustomAttributes.GetFunctionString that specifies the name of a function call to read data.
CustomAttributes.SetFunctionString that specifies the name of a function call to write data.
ImportedDefineCustomAttributes.HeaderFileThe header file that defines the values of code variant preprocessor conditionals. See Variant Systems.
ImportFromFileCustomAttributes.HeaderFileName of header (.h) file containing global variable declarations the code generator imports for the object.
StructCustomAttributes.StructNameName of the struct into which the code generator packs the object's data.

Assigning an Embedded Signal Object to an Output Port.  If you are operating on an embedded signal object with the API, you must copy the object to the port after providing or changing its RTWInfo properties. For example, if MyObj is a signal object that you want to copy to the output port, enter:

hps=get_param(gcb,'PortHandles')
hp=hps.Outport(1)
set_param(hp,'SignalObject','MyObj')

Subsequent changes to the source object in the base workspace have no effect on the output port copy, and you can delete the source object if you have no further use for it:

clear ('MyObj')

Generating Code with Custom Storage Classes

Code Generation Prerequisites

Before you generate code for a model that uses custom storage classes, set model options as follows:

Code Generation Example

This section presents an example of code generation with CSCs, based on this model:

The model contains three named signals: aa, bb, and cc. Using the predefined Struct custom storage class, the example generates code that packs these signals into a struct named mySignals. The struct declaration is then exported to externally written code.

To specify the struct, you provide Simulink.Signal objects that specify the Struct custom storage class, and associate the objects with the signals as described in Applying CSCs to Parameters and Signals. All three objects have the same properties. This figure shows the signal object properties for aa:

The association between identically named model signals and signal objects is formed as described in Resolving Symbols. In this example, the symbols aa, bb, and cc resolve to the signal objects aa, bb, and cc, which have custom storage class Struct. In the generated code, storage for the three signals will be allocated within a struct named mySignals.

You can display the storage class of the signals in the block diagram by selecting Port/Signal Display > Storage Class from the Simulink model editor Format menu. The figure below shows the block diagram with signal data types and signal storage classes displayed.

With the model configured as described in Code Generation Prerequisites, and the signal objects defined and associated with the signals, you can generate code that uses the custom storage classes to generate the desired data structure for the signals. After code generation, the relevant definitions and declarations are located in three files:

Grouped Custom Storage Classes.  A custom storage class that results in multiple data objects being referenced with a single variable in the generated code, in the previous example, is called a grouped custom storage class. In the Simulink package, Bitfield and Struct (shown in the preceding example) are grouped CSCs. Data grouped by a CSC is referred to as grouped data.

Defining Advanced Custom Storage Class Types

Introduction

Certain data layouts, such as nested structures, cannot be generated using the standard Unstructured and FlatStructure custom storage class types. You can define an advanced custom storage class if you want to generate other types of data. Creating advanced CSCs requires understanding TLC programming and using a special advanced mode of the Custom Storage Class Designer. This sections explain how to define advanced CSC types.

Create Your Own Parameter and Signal Classes

The first step is to use the Simulink Data Class Designer to create your own package containing classes derived from Simulink.Parameter or Simulink.Signal. This procedure is described in Creating Packages that Support CSC Definitions.

Add your own object properties and class initialization if desired. For each of your classes, select the Create your own custom storage classes for this class option.

Create a Custom Attributes Class for Your CSC (Optional)

If you have instance-specific properties that are relevant only to your CSC, you should use the Simulink Data Class Designer to create a custom attributes class for the package. A custom attributes class is a subclass of Simulink.CustomStorageClassAttributes. The name, type, and default value properties you set for the custom attributes class define the user view of instance-specific properties.

For example, the ExportToFile custom storage class requires that you set the RTWInfo.CustomAttributes.HeaderFile property to specify a .h file used for exporting each piece of data. See Simulink Package Custom Storage Classes for further information on instance-specific properties.

Write TLC Code for Your CSC

The next step is to write TLC code that implements code generation for data of your new custom storage class. A template TLC file is provided for this purpose. To create your TLC code, follow these steps:

  1. Create a tlc directory inside your package's @directory (if it does not already exist). The naming convention to follow is

    @PackageName/tlc
  2. Copy TEMPLATE_v1.tlc (or another CSC template) from matlabroot/toolbox/rtw/targets/ecoder/csc_templates into your tlc directory to use as a starting point for defining your custom storage class.

  3. Write your TLC code, following the comments in the CSC template file. Comments describe how to specify code generation for data of your custom storage class (for example, how data structures are to be declared, defined, and whether they are accessed by value or by reference).

Alternatively, you can copy a custom storage class TLC file from another existing package as a starting point for defining your custom storage class.

Register Custom Storage Class Definitions

After you have created a package for your new custom storage class and written its associated TLC code, you must register your class definitions with the Custom Storage Class Designer, using its advanced mode.

The advanced mode supports selection of an additional storage class Type, designated Other. The Other type is designed to support special CSC types that cannot be accommodated by the standard Unstructured and FlatStructure custom storage class types. The Other type cannot be assigned to a CSC except when the Custom Storage Class Designer is in advanced mode.

To register your class definitions:

  1. Launch the Custom Storage Class Designer in advanced mode by typing the following command at the MATLAB prompt:

    cscdesigner -advanced
  2. Select your package and create a new custom storage class.

  3. Set the Type of the custom storage class to Other. Note that when you do this, the Other Attributes pane is displayed. This pane is visible only for CSCs whose Type is set to Other.

    If you specify a customized package, additional options, as defined by the package, also appear on the Other Attributes pane.

  4. Set the properties shown on the Other Attributes pane. The properties are:

    • Is grouped: Select this option if you intend to combine multiple data objects of this CSC into a single variable in the generated code. (for example, a struct).

    • TLC file name: Enter the name of the TLC file corresponding to this custom storage class. The location of the file is assumed to be in the /tlc subdirectory for the package, so you should not enter the path to the file.

    • CSC attributes class name: (optional) If you created a custom attributes class corresponding to this custom storage class, enter the full name of the custom attributes class. (see Create a Custom Attributes Class for Your CSC (Optional)).

  5. Set the remaining properties on the General and Comments panes based on the layout of the data that you wish to generate (as defined in your TLC file).

GetSet Custom Storage Class for Data Store Memory

Overview

GetSet is a built-in advanced custom storage class that generates specialized function calls to read from (get) and write to (set) the memory associated with a Data Store Memory block that is read and written many times in a single model. See Working with Data Stores for information about data stores and the Data Store Memory block, and for information about advanced CSCs.

The GetSet custom storage class is designed primarily for use with the state of the Data Store Memory block. However, GetSet is capable of handling signals other than data stores, and is supported for the outputs of most built-in blocks provided by MathWorks. For more about the definition of the GetSet storage class, look at its associated TLC code in the file:

matlabroot\toolbox\simulink\simulink\@Simulink\tlc\GetSet.tlc

GetSet CSC Properties

The next table summarizes the instance-specific properties of the GetSet storage class:

PropertyDescription

GetFunction

String that specifies the name of a function call to read data.

SetFunction

String that specifies the name of a function call to write data.

HeaderFile (optional)

String that specifies the name of a header (.h) file to add as an #include in the generated code.

For example, if the GetFunction of signal X is specified as 'get_X' then the generated code calls get_X() wherever the value of X is used. Similarly, if the SetFunction of signal X is specified as 'set_X' then the generated code calls set_X(value) wherever the value of X is assigned.

Using the GetSet CSC

The GetSet storage class cannot be represented by the standard Unstructured or FlatStructure custom storage class types, so it is an advanced CSC, as described in Defining Advanced Custom Storage Class Types. To access the CSC definition for GetSet, you must launch Custom Storage Class designer in advanced mode:

cscdesigner -advanced

If you omit the HeaderFile property for a GetSet data object, you must specify a header file by an alternative means, such as the Header file field of the Code Generation > Custom Code pane of the Configuration Parameters dialog box. Otherwise, the generated code might not compile or might function improperly.

For wide signals, an additional index argument is passed, so the calls to the get and set functions are get_X(idx) and set_X(idx, value) respectively.

GetSet CSC Restrictions

To use GetSet with a nonsupporting built-in block or a user-written S-function:

  1. Insert a Signal Conversion block at the outport of the block or function.

  2. Select the Signal Conversion Block's Exclude this block from 'Block reduction' optimization property.

  3. Assign the GetSet storage class to the output of the Signal Conversion block.

GetSet Custom Storage Class Example

The model below contains a Data Store Memory block that resolves to the Simulink signal object X:

The following specifications configure the signal object X to use the GetSet custom storage class:

X = Simulink.Signal;
X.RTWInfo.StorageClass                 = 'Custom';
X.RTWInfo.CustomStorageClass           = 'GetSet';
X.RTWInfo.CustomAttributes.GetFunction = 'get_X';
X.RTWInfo.CustomAttributes.SetFunction = 'set_X';
X.RTWInfo.CustomAttributes.HeaderFile  = 'user_file.h';

The GetSet CSC appears as follows in the code generated for the model:

/* Includes for objects with custom storage classes. */
   #include "user_file.h"

   void getset_csc_step(void)
   {
     /* local block i/o variables */
     real_T rtb_DSRead_o;
   
     /* DataStoreWrite: '<Root>/DSWrite' incorporates:
      *   Inport: '<Root>/In1'
      */
     set_X(getset_csc_U.In1);
   
     /* DataStoreRead: '<Root>/DSRead' */
     rtb_DSRead_o = get_X();
   
     /* Outport: '<Root>/Out1' */
     getset_csc_Y.Out1 = rtb_DSRead_o;
   }

Note that the code uses a local variable rtb_DSRead_o rather than multiple calls to the get_X function. This technique increases code efficiency and prevents changes to the value within a simulation step.

Custom Storage Class Implementation

You can skip this section unless you want to ship custom storage class definitions in an uneditable format, or you intend to bypass the Custom Storage Class designer and work directly with files that contain custom storage class definitions.

The file that defines a package's custom storage classes is called a CSC registration file. The file is always named csc_registration and resides in the @package directory that defines the package. A CSC registration file can be a P-file (csc_registration.p) or a MATLAB file (csc_registration.m). A built-in package defines custom storage classes in both a P-file and a functionally equivalent MATLAB file. A user-defined package initially defines custom storage classes only in a MATLAB file.

P-files take precedence over MATLAB files, so when MATLAB looks for a package's CSC registration file and finds both a P-file and a MATLAB file, MATLAB loads the P-file and ignores the MATLAB file. All capabilities and tools, including the Custom Storage Class Designer, then use the CSC definitions stored in the P-file. P-files cannot be edited, so all CSC Designer editing capabilities are disabled for CSCs stored in a P-file. If no P-file exists, MATLAB loads CSC definitions from the MATLAB file. MATLAB files are editable, so all CSC Designer editing capabilities are enabled for CSCs stored in a MATLAB file.

Because CSC definitions for a built-in package exist in both a P-file and a MATLAB file, they are uneditable. You can make the definitions editable by deleting the P-file, but MathWorks strongly discourages modifying built-in CSC registration files or any other files under matlabroot. The preferred technique is to create user-defined packages, data classes, and custom storage classes, as described in Subclassing Simulink Data Classes and this chapter.

The CSC Designer saves CSC definitions for user-defined packages in a MATLAB file, so the definitions are editable. You can make the definitions uneditable by using the pcode function to create an equivalent P-file, which will then shadow the MATLAB file. However, you should preserve the MATLAB file if you may need to make further changes, because you cannot modify CSC definitions that exist only in a P-file.

You can also use tools or techniques other than the Custom Storage Class Designer to create and edit MATLAB files that define CSCs. However, MathWorks discourages this practice, which is vulnerable to syntax errors and can give unexpected results. When MATLAB finds an older P-file that shadows a newer MATLAB file, it displays a warning in the MATLAB Command Window.

Custom Storage Class Limitations

  


Related Products & Applications

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