Main Content

Custom Function Code Replacement

This example shows how to replace a custom function from your model with a different function in the generated code. Use this replacement when your model uses a MATLAB Function block to call a function for simulation and you want the generated code to use a different version of the function that is optimized for your code generation target. You can replace a function in these scenarios:

  • The MATLAB function uses the coder.ceval function to call a custom C function.

  • The MATLAB function uses the coder.replace function to indicate that you want to replace a call to a custom MATLAB function.

To replace a custom function, define a custom entry in a code replacement library.

Interactively Develop a Code Replacement Library

Specify a code replacement entry for a custom C function by using the Code Replacement Tool.

  1. At the MATLAB command prompt, open the Code Replacement Tool by using the crtool command.

    crtool

  2. Create a table. From the crtool context menu, select File > New Table.

  3. Create an entry. From the crtool context menu, select File > New entry > Function.

  4. Create entry parameters. In the Function drop-down list, select Custom. Next to the drop-down list, specify the name of the function that you want to replace. For this example, set the function name to doubleIt.

  5. Create the conceptual representation. The conceptual representation describes the signature of the function that you want to replace. In the Conceptual function subsection, add the return argument y1 and the input argument u1. For both arguments, specify the Data Type of double and the Argument Type of scalar. For this example, to specify that the implementation arguments have the same order and properties as the conceptual arguments, select the Make conceptual and implementation argument types the same check box.

  6. Create the implementation representation. In the Replacement function > Function prototype section, specify the name of the replacement function. For this example, set the name to custom_doubleIt. In the Function arguments section, add the return argument y1 and the input argument u1.

  7. Optionally, specify build information. Click the Build Information tab to open the build requirements pane. Specify the files (source, header, object) that the code generator requires for code replacement. For this example, specify the source file custom_doubleIt.c and the header file custom_doubleIt.h.

  8. Validate and save the table. Click the Mapping Information tab and verify that the fields are filled in as shown. Click Validate entry. In the crtool context menu, select File > Save table > Save and name the table customCRL.m.

    Code replacement tools showing a custom function entry.

  9. Register a code replacement library. Registration creates a library composed of the tables that you specify. Select File > Generate registration file. In the Generate registration file dialog box, specify the registry name Custom Function CRL and the table list customCRL. To use your code replacement library, refresh your current MATLAB session by using the command sl_refresh_customizations.

    sl_refresh_customizations

  10. Verify the code replacement library. At the MATLAB command prompt, open the library by using the Code Replacement Viewer and verify that the table and entry are correctly specified.

Programmatically Develop a Code Replacement Library

Programmatically specify a code replacement entry for a custom C function.

  1. Open the programmatic interface from the MATLAB menu by selecting New > Function.

  2. Create a table.

    1. Create a function that has the name of your code replacement library table, which does not have arguments and returns a table object. Use this function to call your code replacement library table.

    2. Create a table object by calling RTW.TflTable.

    function hTable = crl_table_custom()
    % Create a function to call the code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
  3. Create an entry. Because this example replaces a function, create a code replacement entry in your table by calling the entry function RTW.TflCFunctionEntry.

    function hTable = crl_table_custom()
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry
    hEntry = RTW.TflCFunctionEntry;
    
  4. Create entry parameters. Because this example replaces a function, create entry parameters by calling the function setTflCFunctionEntryParameters.

    function hTable = crl_table_custom()
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry
    hEntry = RTW.TflCFunctionEntry;
    
    %% Create entry parameters
    hEntry.setTflCFunctionEntryParameters( ...
              'Key', 'doubleIt', ...
              'ImplementationName', 'custom_doubleIt', ...
              'ImplementationHeaderFile', 'custom_doubleIt.h', ...
              'ImplementationSourceFile', 'custom_doubleIt.c');
  5. Create the conceptual representation. The conceptual representation describes the signature of the function that you want to replace. To explicitly specify argument properties, call the function getTflArgFromString.

    function hTable = crl_table_custom()
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry
    hEntry = RTW.TflCFunctionEntry;
    
    %% Create entry parameters
    hEntry.setTflCFunctionEntryParameters( ...
              'Key', 'doubleIt', ...
              'ImplementationName', 'custom_doubleIt', ...
              'ImplementationHeaderFile', 'custom_doubleIt.h', ...
              'ImplementationSourceFile', 'custom_doubleIt.c');
    
    %% Create the conceptual representation
    arg = getTflArgFromString(hTable, 'y1', 'double');
    arg.IOType = 'RTW_IO_OUTPUT';
    addConceptualArg(hEntry, arg);
    
    arg = getTflArgFromString(hTable, 'u1', 'double');
    arg.IOType = 'RTW_IO_INPUT';
    addConceptualArg(hEntry, arg);
  6. Create the implementation representation. The implementation representation describes the signature of the optimization function. To specify that the implementation arguments have the same order and properties as the conceptual arguments, call the function copyConceptualArgsToImplementation. Add the entry to the table by calling the function addEntry.

    function hTable = crl_table_custom()
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry
    hEntry = RTW.TflCFunctionEntry;
    
    %% Create entry parameters
    hEntry.setTflCFunctionEntryParameters( ...
              'Key', 'doubleIt', ...
              'ImplementationName', 'custom_doubleIt', ...
              'ImplementationHeaderFile', 'custom_doubleIt.h', ...
              'ImplementationSourceFile', 'custom_doubleIt.c');
    
    %% Create the conceptual representation
    arg = getTflArgFromString(hTable, 'y1', 'double');
    arg.IOType = 'RTW_IO_OUTPUT';
    addConceptualArg(hEntry, arg);
    
    arg = getTflArgFromString(hTable, 'u1', 'double');
    arg.IOType = 'RTW_IO_INPUT';
    addConceptualArg(hEntry, arg);
    
    %% Create the implementation representation
    copyConceptualArgsToImplementation(hEntry);
    
    %% Add the entry to the table
    hTable.addEntry(hEntry);
    end
  7. Specify build information. In the entry parameters, specify files (header, source, object) that the code generator requires for code replacement. For this example, build information is not required.

  8. Validate and save the customization file. From the MATLAB menu, save this customization file by selecting File > Save. At the command prompt, validate the code replacement library table by calling it:

    >> hTable = crl_table_custom
  9. Register the code replacement library. Registration creates a code replacement library by defining the library name, code replacement tables, and other information. Create a registration file by using these specifications:

    function rtwTargetInfo(cm)
     
    cm.registerTargetInfo(@loc_register_crl);
    end
     
    function this = loc_register_crl 
     
    this(1) = RTW.TflRegistry; 
    this(1).Name = 'Custom Function CRL';
    this(1).TableList = {'crl_table_custom.m'}; % table created in this example
    this(1).TargetHWDeviceType = {'*'};
    this(1).Description = 'Example code replacement library';
    
    end
    

    To use your code replacement library, refresh your current MATLAB session with the command:

    >>sl_refresh_customizations

  10. Verify the code replacement library. At the command prompt, open the library by using the Code Replacement Viewer and verify that the table and entry are correctly specified. For more information, see Verify Code Replacement Library. Configure your model to use the code replacement library, generate code, and verify that replacement occurs as expected. If unexpected behavior occurs, examine the hit and miss logs to troubleshoot the issues.

Generate Code by Using Custom Function Code Replacement

Generate code using the code replacement library that you previously created. A custom C function that is called in a MATLAB Function block is replaced with a call to a different custom function in the generated code.

Example Model

Open the model myDoubleModel for configuring the code replacement library.

open_system('myDoubleModel')

The MATLAB Function block in the model uses the coder.ceval function to call the custom C function doubleIt.

function y = fcn(u)

y = 0.0;

y = coder.ceval('doubleIt',u);

The code replacement library replaces this function with a call to the custom function custom_doubleIt. For this example, the code replacement table is saved in the file customCRL.m and the library is registered in the registration file rtwTargetInfo.m.

To use the code replacement library, refresh the current MATLAB session.

copyfile targetInfoFile/rtwTargetInfo.m
sl_refresh_customizations

Enable Code Replacement Library

Configure the model to use the code replacement library and generate code.

  1. Open the Configuration Parameters dialog box. On the Modeling tab, click Settings.

  2. On the Code Generation > Interface pane, for the Code replacement libraries parameter, click Select. Select the code replacement library Custom Function CRL and click OK.

% Alternatively, use the command-line API to enable the code replacement:
set_param('myDoubleModel', 'CodeReplacementLibrary', 'Custom Function CRL');

Generate code for the model. Press Ctrl+B or open the Embedded Coder app and click Generate Code.

evalc('slbuild(bdroot)');

In the Code view, confirm that the step function calls the custom C function custom_doubleIt.

cfile = fullfile('myDoubleModel_ert_rtw','myDoubleModel.c');
coder.example.extractLines(cfile,'/* Model step function ','/* Model initialize function',1, 1);
/* Model step function */
void myDoubleModel_step(void)
{
  /* Outport: '<Root>/y' incorporates:
   *  Inport: '<Root>/u'
   *  MATLAB Function: '<Root>/MATLAB Function'
   */
  myDoubleModel_Y.y = custom_doubleIt(myDoubleModel_U.u);
}

The function doubleIt is replaced with the custom function custom_doubleIt.

Related Topics