Call C Functions Using C Caller Block
This example shows how to use the C Caller block to call your handwritten C functions in Simulink®.
In this example, five custom C functions are defined in my_func.h
and implemented in my_func.c
.
Import C structure and enumeration types used by custom code
The C Caller block supports C structure and enumeration types. Use command Simulink.importExternalCTypes
to import these types into Simulink as matching Simulink.Bus
objects or Simulink.IntEnumType
classes. This imports the Bus types LIMITBUS
and COUNTERBUS
and the Enum type TrafficLightColor
. The types appear in the MATLAB workspace.
Simulink.importExternalCTypes('my_func.h', 'EnumClass', 'dynamic');
Open the model
model = 'slexCCallerExample';
open_system(model);
Add header file to Simulation Target configuration
Specify your custom header and source files in the Simulation Target pane of the Model Configuration Parameters. Specify absolute paths or paths relative to your model's directory or the current MATLAB directory.
Use C preprocessor syntax in the "Include headers" pane to include your custom header files. For example, to include the my_func.h
header, enter this line:
#include "my_func.h"
configset.highlightParameter(model, "SimCustomHeaderCode");
Add source file to Simulation Target configuration
Use a space-separated list of source files in the "Source files" pane of the Simulation Target configuration. If a filename contains spaces, surround it in double quotes, such as: "my c file.c"
.
configset.highlightParameter(model, "SimUserSources");
Simulate the model
When you simulate the model, Simulink calls your custom C functions at each timestep.
sim(model);