Call External Functions with coder.ceval

Workflow for Calling External Functions

To call external C/C++ functions from generated code:

  1. Write your C/C++ functions in external source files or libraries.

  2. Create header files, if required.

    The header file defines the data types used by the C/C++ functions that MATLAB® Coder™ generates in code, as described in Mapping MATLAB Types to C/C++ Types.

      Tip   One way to add these type definitions is to include the header file tmwtypes.h, which defines general data types supported by MATLAB. This header file is in matlabroot/extern/include. Check the definitions in tmwtypes.h to determine if they are compatible with your target. If not, define these types in your own header files.

  3. In your MATLAB function, add calls to coder.ceval to invoke your external C/C++ functions.

    You need one coder.ceval statement for each call to a C/C++ function. In your coder.ceval statements, use coder.ref, coder.rref, and coder.wref constructs as required (see Pass Arguments by Reference to External Functions).

  4. Include the custom C/C++ functions in the build. See Specify External File Locations.

  5. Check for compilation warnings about data type mismatches.

    Perform this check so that you catch type mismatches between C/C++ and MATLAB (see How MATLAB Coder Infers C/C++ Data Types).

  6. Generate code and fix errors.

  7. Run your application.

Best Practices for Calling External Code from Generated Code

The following are recommended practices when calling C/C++ code from generated code.

  • Start small. — Create a test function and learn how coder.ceval and its related constructs work.

  • Use separate files. — Create a file for each C/C++ function that you call. Make sure that you call the C/C++ functions with suitable types.

  • In a header file, declare a function prototype for each function that you call, and include this header file in the generated code. For more information, see Specify External File Locations.

Was this topic helpful?