| Contents | Index |
| On this page… |
|---|
Include External C Functions in a Model Create a Block That Calls a C Function Validate External Code in the Simulink Environment Validate C Code as Part of a Model |
Evaluate a C function as part of a model simulation.
Call an external C function from generated code.
Ability to open and modify Simulink models and subsystems.
Ability to set model configuration parameters.
Ability to read C code.
Set up a C compiler. In the MATLAB Command Window, enter mex -setup and specifying a valid, installed compiler.
rtwdemo_throttlecntrl_extfunccall.mdl
rtwdemo_ValidateLegacyCodeVrsSim.mdl
/toolbox/rtw/rtwdemos/EmbeddedCoderOverview/stage_4_files/SimpleTable.c
/toolbox/rtw/rtwdemos/EmbeddedCoderOverview/stage_4_files/SimpleTable.h
Simulink models are one part of Model-Based Design. For many applications, a design also includes a set of preexisting C functions created, tested (verified), and validated outside of a MATLAB and Simulink environment. You can integrate these functions easily into a model and the generated code. External C code can be used in the generated code to access hardware devices and external data files during rapid simulation runs.
This example shows you how to create a custom block that calls an external C function. Once the block is part of the model, you can take advantage of the simulation environment to test the system further.
To specify a call to an external C function, use an S-Function block. You can automate the process of creating the S-Function block by using the Simulink Legacy Code Tool. Using this tool, you specify an interface for your external C function. The tool then uses that interface to automate creation of an S-Function block.
Make copies of the files SimpleTable.c and SimpleTable.h, located in matlabroot/toolbox/rtw/rtwdemos/EmbeddedCoderOverview/stage_4_files. Put the copies in your working folder.
Create an S-Function block that calls the specified function at each time step during simulation:
In the MATLAB Command Window, create a function interface definition structure:
def=legacy_code('initialize')The data structure def defines the function interface to the external C code.
def =
SFunctionName: ''
InitializeConditionsFcnSpec: ''
OutputFcnSpec: ''
StartFcnSpec: ''
TerminateFcnSpec: ''
HeaderFiles: {}
SourceFiles: {}
HostLibFiles: {}
TargetLibFiles: {}
IncPaths: {}
SrcPaths: {}
LibPaths: {}
SampleTime: 'inherited'
Options: [1x1 struct]Populate the function interface definition structure by entering the following commands:
def.OutputFcnSpec=['double y1 = SimpleTable(double u1,',...
'double p1[], double p2[], int16 p3)'];
def.HeaderFiles = {'SimpleTable.h'};
def.SourceFiles = {'SimpleTable.c'};
def.SFunctionName = 'SimpTableWrap';Create the S-function:
legacy_code('sfcn_cmex_generate', def)Compile the S-function:
legacy_code('compile', def)Create the S-Function block:
legacy_code('slblock_generate', def)A new model window opens that contains the SimpTableWrap block.
Save the model to your working folder as: s_func_simptablewrap.mdl.
Create a Target Language Compiler (TLC) file for the S-Function block:
legacy_code('sfcn_tlc_generate', def)The TLC file is the component of an S-function that specifies how the code generator produces the code for a block.
For more information on using the Legacy Code Tool, see:
Integrating Existing C Functions into Simulink Models with the Legacy Code Tool in the Simulink documentation
When you integrate external C code with a Simulink model, before using the code, always validate the functionality of the external C function code as a standalone component.
Open the model rtwdemo_ValidateLegacyCodeVrsSim.mdl. This model validates the S-function block that you just created.

The Sine Wave block produces output values from [-2 : 2].
The input range of the lookup table is from [-1 : 1].
The output from the lookup table is the absolute value of the input.
The lookup table output clips the output at the input limits.
Simulate the model.
View the validation results by opening the Validation subsystem and, in that subsystem, clicking the Scope block.
The following figure shows the validation results. The external C code and the Simulink Lookup table block provide the same output values.

Close the validation model.
After you validate the functionality of the external C function code as a standalone component, validate the S-function in the model. Use the test harness model to complete the validation.
Open rtwdemo_throttlecntrl_extfunccall.mdl and save a copy as throttlecntrl_extfunccall.mdl in a writable folder on your MATLAB path.
Examine the PI_ctrl_1 and PI_ctrl_2 subsystems.
Lookup blocks have been replaced with the block you created using the Legacy Code Tool.
Note the block parameter settings for SimpTableWrap and SimpTableWrap1.
Close the Block Parameter dialog boxes and the PI subsystem windows.
Open the test harness model, right-click the Unit_Under_Test Model block, and select Model Reference Parameters.
Set Model name (without the .mdl extension) to throttlecntrl_extfunccall. Click OK.
Update the test harness model diagram.
Simulate the test harness.
The simulation results match the expected golden values.

Save and close throttlecntrl_extfunccall.mdl and rtwdemo_throttlecntrl_testharness.mdl.
The code generator uses a TLC file to process the S-Function block. Calls to C code embedded in an S-Function block:
Can use data objects.
Are subject to expression folding, an operation that combines multiple computations into a single output calculation.
Open rtwdemo_throttlecntrl_extfunccall.mdl.
Generate code for the model.
Examine the generated code in the filethrottlecntrl_extfunccall.c.
The following code fragment shows code for a Lookup Table block before you replaced the block with the external SimpleTable function:
throttlecntrl_extfunccall_B.Discrete_Time_Integrator1 = throttlecntrl_extfunccall_P.I_Gain *
rt_Lookup((const real_T *)throttlecntrl_extfunccall_P.I_InErrMap, 9, rtb_Sum3,
(const real_T *)throttlecntrl_extfunccall_P.I_OutMap) * rtb_Sum3 * 0.001 +
throttlecntrl_extfunccall_DWork.Discrete_Time_Integrator1_DSTAT;After you integrate the SimpleTable function, the generated code appears as follows:
throttlecntrl_extfunccall_B.Discrete_Time_Integrator1 = throttlecntrl_extfunccall_P.I_Gain *
SimpleTable( (real_T)rtb_Sum2, (real_T*)throttlecntrl_extfunccall_P.I_InErrMap, (real_T*)
throttlecntrl_extfunccall_P.I_OutMap, (int16_T)9) * rtb_Sum2 * 0.001 +
throttlecntrl_extfunccall_DWork.Discrete_Time_Integrator1_DSTAT;Close throttlecntrl_extfunccall.mdl and throttlecntrl_testharness.mdl.
You can easily integrate external functions into a model and generated code by using the Legacy Code Tool.
Always validate the functionality of external C function code which you integrate into a model as a standalone component.
After you validate the functionality of external C function code as a standalone component, validate the S-function in the model.
Integrating Existing C Functions into Simulink Models with the Legacy Code Tool in the Simulink documentation
Insert S-Function Code in the Simulink Coder documentation
![]() | Configure the Data Interface |

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 |