Matlab External
Matlab External
External Interfaces
R2021b
How to Contact MathWorks
Phone: 508-647-7000
v
matlab::data::DuplicateFieldNameInStructArrayException . . . . . . . . . . . 2-13
matlab::data::FailedToLoadLibMatlabDataArrayException . . . . . . . . . . . 2-13
matlab::data::FailedToResolveSymbolException . . . . . . . . . . . . . . . . . . . 2-13
matlab::data::InvalidArrayIndexException . . . . . . . . . . . . . . . . . . . . . . . 2-13
matlab::data::InvalidDimensionsInSparseArrayException . . . . . . . . . . . . 2-13
matlab::data::InvalidFieldNameException . . . . . . . . . . . . . . . . . . . . . . . . 2-13
matlab::data::MustSpecifyClassNameException . . . . . . . . . . . . . . . . . . . 2-13
matlab::data::NonAsciiCharInRequestedAsciiOutputException . . . . . . . . 2-13
matlab::data::NonAsciiCharInInputDataException . . . . . . . . . . . . . . . . . 2-13
matlab::data::InvalidArrayTypeException . . . . . . . . . . . . . . . . . . . . . . . . 2-14
matlab::data::NotEnoughIndicesProvidedException . . . . . . . . . . . . . . . . 2-14
matlab::data::StringIndexMustBeLastException . . . . . . . . . . . . . . . . . . . 2-14
matlab::data::StringIndexNotValidException . . . . . . . . . . . . . . . . . . . . . . 2-14
matlab::data::SystemErrorException . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
matlab::data::TooManyIndicesProvidedException . . . . . . . . . . . . . . . . . . 2-14
matlab::data::TypeMismatchException . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
matlab::data::WrongNumberOfEnumsSuppliedException . . . . . . . . . . . . 2-14
matlab::data::InvalidMemoryLayoutException . . . . . . . . . . . . . . . . . . . . 2-14
matlab::data::InvalidDimensionsInRowMajorArrayException . . . . . . . . . 2-14
matlab::data::NumberOfElementsExceedsMaximumException . . . . . . . . 2-14
matlab::data::ObjectArrayIncompatibleTypesException . . . . . . . . . . . . . 2-15
matlab::data::AccessingObjectNotSupportedException . . . . . . . . . . . . . . 2-15
matlab::data::InvalidNumberOfElementsProvidedException . . . . . . . . . . 2-15
matlab::data::FeatureNotSupportedException . . . . . . . . . . . . . . . . . . . . 2-15
vi Contents
Java Objects Are References in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Use ArrayList Object in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
vii
Construct and Concatenate Java Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34
Create Java Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34
Concatenate Objects of Same Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34
Concatenate Objects of Unlike Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34
viii Contents
Read and Write MATLAB MAT-Files in C/C++ and Fortran
4
Choosing Applications to Read and Write MATLAB MAT-Files . . . . . . . . . 4-2
Copy External Data into MAT-File Format with Standalone Programs . . . 4-8
Overview of matimport.c Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
Declare Variables for External Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
Create mxArray Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Create MATLAB Variable Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Read External Data into mxArray Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Create and Open MAT-File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Write mxArray Data to File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Clean Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Build the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Create the MAT-File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Import Data into MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11
ix
Calling Functions in C++ Shared Libraries from MATLAB
5
What Types of Files Define Your Library? . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
x Contents
Define Scalar Object Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-30
Define Matrix Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-30
Define String Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-31
Define Typed Pointer Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-33
Use Property or Method as SHAPE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-33
xi
User-Defined Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-55
nullptr Argument Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-57
void* Argument Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-57
Unsupported Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-59
xii Contents
Use Function and Member Function Templates . . . . . . . . . . . . . . . . . . . . 5-91
Overloaded Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-91
Unique Function Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-91
xiii
Call Library Functions on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-114
Set System Path to Library File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-114
Set MATLAB Path to Interface Folder . . . . . . . . . . . . . . . . . . . . . . . . . . 5-114
View Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-114
Call Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-114
xiv Contents
Limitations to Shared Library Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
MATLAB Supports C Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
Loading C++ Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
Limitations Using printf Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
Bit Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
Enum Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
Unions Not Supported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
Compiler Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
Limitations Using Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
Functions with Variable Number of Input Arguments Not Supported . . . . . 6-8
xv
Pass Arrays Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-30
print2darray Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-30
Convert MATLAB Array to C-Style Dimensions . . . . . . . . . . . . . . . . . . . . 6-30
multDoubleArray Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-31
Preserve 3-D MATLAB Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-31
Intro to MEX-Files
7
Choosing MEX Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
C++ MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
C/C++ MEX Functions for MATLAB R2017b and Earlier . . . . . . . . . . . . . . 7-2
Fortran MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
MEX Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
xvi Contents
Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
Using Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
xvii
Must I Update My Source MEX Files? . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-36
xviii Contents
Getting Help When MEX Fails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-60
Errors Finding Supported Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-60
Errors Building MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-60
Preview mex Build Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-60
C/C++ MEX-Files
8
Components of C MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
mexFunction Gateway Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Naming the MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Required Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Managing Input and Output Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Validating Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
Computational Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
xix
Create C Source MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9
Handle 8-, 16-, 32-, and 64-Bit Data in C MEX File . . . . . . . . . . . . . . . . . 8-33
xx Contents
Debug on Mac Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
Using Xcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
Using LLDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-41
xxi
Create a C++ MEX Source File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Create Source File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Add Required Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Using Convenience Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Define MexFunction Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Define operator() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5
Add Member Function to Check Arguments . . . . . . . . . . . . . . . . . . . . . . . 9-5
Implement Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
Setup and Build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7
Call MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7
xxii Contents
Modify Cell Array in MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-32
Modify Structure in MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-34
xxiii
Making async Requests Using mexCallMATLAB . . . . . . . . . . . . . . . . . . . . 9-68
xxiv Contents
Calling MATLAB Engine from C/C++ and Fortran Programs
11
Choosing Engine Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
xxv
Can't Start MATLAB Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-26
xxvi Contents
When to Specify Number of Output Arguments . . . . . . . . . . . . . . . . . . . 12-17
xxvii
Java Integer to MATLAB double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-37
xxviii Contents
Pass Data to MATLAB from Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-21
Python Type to MATLAB Scalar Type Mapping . . . . . . . . . . . . . . . . . . . 13-21
Python Container to MATLAB Array Type Mapping . . . . . . . . . . . . . . . . 13-21
Unsupported Python Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-21
xxix
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-4
MATLABEngine Member Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-5
Exception Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-5
Data Size Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-6
Using Engine in Multiple-Thread Environment . . . . . . . . . . . . . . . . . . . . 14-6
xxx Contents
Create Structure Arrays from C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-36
Create Structure Array and Send to MATLAB . . . . . . . . . . . . . . . . . . . . 14-36
Get Structure from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-37
Access Struct Array Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-37
xxxi
Using the delete Function on a .NET Object . . . . . . . . . . . . . . . . . . . . . 15-18
xxxii Contents
Pass Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-46
Pass MATLAB Arrays as Jagged Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 15-46
xxxiii
Determining Which Overloaded Method Is Invoked . . . . . . . . . . . . . . . . 15-74
Support for ByRef Attribute in VB.NET . . . . . . . . . . . . . . . . . . . . . . . . . 15-74
xxxiv Contents
Testing for Membership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-94
xxxv
Using COM Objects from MATLAB
16
MATLAB COM Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2
Concepts and Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2
COM Objects, Clients, and Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2
MATLAB COM Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2
MATLAB COM Automation Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-3
xxxvi Contents
Enumerated Values for Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10
Property Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10
Custom Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-11
Properties That Take Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-11
xxxvii
MATLAB COM Automation Server Support
18
Register MATLAB as COM Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
When to Register MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
Register MATLAB for Current User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
Register MATLAB for All Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-3
Register from Operating System Prompt . . . . . . . . . . . . . . . . . . . . . . . . . 18-3
Unregister MATLAB as COM Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-3
xxxviii Contents
Call PricesStreamer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5
xxxix
Python Interface Topics
20
Access Python Modules from MATLAB - Getting Started . . . . . . . . . . . . . 20-2
Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Verify Python Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Access Python Standard Library Modules in MATLAB . . . . . . . . . . . . . . . 20-3
Display Python Documentation in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 20-3
Create List, Tuple, and Dictionary Types . . . . . . . . . . . . . . . . . . . . . . . . . 20-3
Precedence Order of Methods and Functions . . . . . . . . . . . . . . . . . . . . . 20-4
Access Other Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-4
Python Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-4
xl Contents
Python Tries to Execute myfunc in Wrong Module . . . . . . . . . . . . . . . . 20-27
System Commands
21
Shell Escape Function Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-2
xli
Specify Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3
Run UNIX Programs off System Path . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-4
Run AppleScript on macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-5
Settings
22
Access and Modify Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2
Access Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2
Modify Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-3
Restore Default Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-3
Settings and Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-4
xlii Contents
1
• Call C++ Library Functions - To call functions in a C++ shared library, use the clib package
described in “C++ Libraries in MATLAB”.
• Whenever possible, choose the C++ interface over the C-only interface. For information about
C++ support, see these limitations on page 5-40.
• To call functions in a C shared library, use the calllib function. For information, see “C
Libraries in MATLAB”. This feature works best with C-only libraries, but has these limitations
on page 6-6.
If you want more control over data conversion and memory management, consider writing a MEX
file.
• A MEX file is wrapper code around a C/C++ algorithm that handles the conversion of MATLAB
data types to C types. MEX files provide better performance than calling functions through
MATLAB shared library interfaces. Also, MEX files give you more programmatic control over data
conversion and memory management.
• “C++ MEX Applications” use modern C++ programming features and, where possible, shared
copies of data.
• “C MEX File Applications” use the “C Matrix API” and is supported for existing MEX functions.
MathWorks recommends that whenever possible, choose C++ MEX over C MEX file
applications. However, if your MEX functions must run in MATLAB R2017b or earlier, then
write MEX functions with the C matrix library.
• If you have multiple functions in a library or do not have performance issues, consider writing
a C++ library interface.
These features require C/C++ programming skills to create a library interface or to write a MEX
function. However, you can give the resulting library or MEX function to any MATLAB user. The end
user calls the functionality like any MATLAB function, without knowing the underlying details of the
C/C++ language implementation.
To call MATLAB from a C/C++ language program, see “MATLAB Engine API for C++” or “MATLAB
Engine API for C”.
1-2
Integrate MATLAB with External Programming Languages and Systems
MATLAB supports calling functions and using objects in the following languages.
To create an engine application, install a compiler that MATLAB supports and use the mex command
to build the application.
To create a MEX file, install a compiler that MATLAB supports and use the mex command to build the
function.
1-3
1 External Programming Languages and Systems
• MATLAB RESTful web services functions allow non-programmers to access many web services
using HTTP GET and POST methods.
• For functionality not supported by the RESTful web services functions, use the HTTP Interface
classes for writing customized web access applications.
• If your web service is based on Web Services Description Language (WSDL) document
technologies, then use the MATLAB WSDL functions.
See Also
More About
• “External Language Interfaces”
External Websites
• MATLAB Supported Interfaces to Other Languages
• Supported and Compatible Compilers
1-4
Custom Linking to Required API Libraries
To custom build these applications using an Integrated Development Environment (IDE) instead of
the mex command, refer to this list of required run-time libraries and include files. To identify path
names, use these MATLAB commands.
Include files:
Windows® libraries:
• matlabroot\extern\lib\win64\compiler\libMatlabDataArray.lib
Linux® libraries:
• Linux—matlabroot/extern/bin/glnxa64/libMatlabDataArray.so
macOS libraries:
• macOS—matlabroot/extern/bin/maci64/libMatlabDataArray.dylib
Include files:
Windows libraries:
Linux libraries:
1-5
1 External Programming Languages and Systems
macOS libraries:
C MEX Functions
To build C MEX functions, use the “C Matrix API” and C MEX API functions listed in “C MEX File
Applications”. Optionally, to read or write to MAT-files in your MEX functions, use the “MATLAB C API
to Read MAT-File Data”.
Include files:
Windows libraries:
• matlabroot\extern\lib\win64\compiler\libmex.lib
• matlabroot\extern\lib\win64\compiler\libmx.lib
• matlabroot\extern\lib\win64\compiler\libmat.lib (optional)
Linux libraries:
• matlabroot/bin/glnxa64/libmex.so
• matlabroot/bin/glnxa64/libmx.so
• matlabroot/bin/glnxa64/libmat.so (optional)
macOS libraries:
• matlabroot/bin/maci64/libmex.dylib
• matlabroot/bin/maci64/libmx.dylib
• matlabroot/bin/maci64/libmat.dylib (optional)
C Engine Applications
To build C engine applications, use the “C Matrix API” and “MATLAB Engine API for C”. If you
include C MEX API functions such as mexPrintf in you application, then you must link to the
libmex library. For a list of functions, see “C MEX File Applications”. Optionally, to read or write
MAT-files in your application, use the “MATLAB C API to Read MAT-File Data”.
Include files:
1-6
Custom Linking to Required API Libraries
• matrix.h — Definition of the mxArray structure and function prototypes for matrix access
routines
• mat.h (optional) — Function prototypes for mat routines
Windows libraries:
Linux libraries:
macOS libraries:
C MAT-File Applications
To build standalone applications to read data from C MAT-files, use the “C Matrix API” and “MATLAB
C API to Read MAT-File Data”. If you include C MEX API functions such as mexPrintf in you
application, then you must link to the libmex library. For a list of these functions, see “C MEX File
Applications”.
Include files:
Windows libraries:
Linux libraries:
1-7
1 External Programming Languages and Systems
macOS libraries:
See Also
mex
More About
• “Build C++ Engine Programs” on page 14-7
• “Build Engine Applications with IDE” on page 11-24
• “MAT-File API Library and Include Files” on page 4-5
External Websites
• Compiling MEX Files without the mex Command
1-8
2
Create Arrays
The C++ MATLAB Data API lets applications running outside of MATLAB work with MATLAB data
through a MATLAB-neutral interface. The API uses modern C++ semantics and design patterns and
avoids data copies whenever possible by using MATLAB copy-on-write semantics.
The matlab::data::Array class is the base class for all array types. It provides general array
information, such as type and size. The Array class supports both one-dimensional and multi-
dimensional arrays. The MATLAB Data API uses zero-based indexing.
matlab::data::ArrayFactory factory;
Use the factory to create a 2-by-2 array of type double. Specify the array values in column-major
format to match the ordering of the MATLAB statement A = [1 2; 3 4]. To inspect the array, use
the functions in the matlab::data::Array class.
#include "MatlabDataArray.hpp"
int main() {
using namespace matlab::data;
ArrayFactory factory;
Array A = factory.createArray<double>({ 2,2 },
{ 1.0, 3.0, 2.0, 4.0 });
// Inspect array
ArrayType c = A.getType();
ArrayDimensions d = A.getDimensions();
size_t n = A.getNumberOfElements();
return 0;
}
A = [1 2; 3 4];
c = class(A);
d = size(A);
n = numel(A);
The matlab::data::TypedArray class supports iterators, which enable you to use range-based
for loops. This example creates a 1-by-6 array from the 3-by-2 TypedArray.
#include "MatlabDataArray.hpp"
2-2
Create Arrays with C++ MATLAB Data API
int main() {
using namespace matlab::data;
ArrayFactory factory;
return 0;
}
#include "MatlabDataArray.hpp"
int main() {
using namespace matlab::data;
ArrayFactory factory;
return 0;
}
See Also
createArray | matlab::data::TypedArray
2-3
2 External Data Interface (EDI)
#include "MatlabDataArray.hpp"
int main() {
using namespace matlab::data;
ArrayFactory factory;
CharArray A = factory.createCharArray("This is a char array.");
CharArray C = factory.createCharArray("");
// Copy the contents of A into C
C = A;
return 0;
}
Array supports copy-on-write semantics. Copies of an Array object are unshared when a write
operation is performed. In the previous example, modifying the variable B creates a copy of the
CharArray object with updated data. However, A and C remain shared copies.
C++ MATLAB Data Arrays support move semantics. When you pass a variable using move, there is
no copy of the variable.
See Also
createCharArray
2-4
C++ Cell Arrays
Create a CellArray that is equivalent to a MATLAB cell array defined with this MATLAB statement.
Note that MATLAB assigns the cells in column-major order.
C = {'Character Array',...
[true true false true];...
[2.2 3.3 -4.2 6.0],...
int32(-3374)};
Create an ArrayFactory:
matlab::data::ArrayFactory factory;
Call createCellArray and define each cell contained in the cell array:
matlab::data::CellArray C = factory.createCellArray({ 2,2 },
factory.createCharArray("Character Array"),
factory.createArray<double>({ 1, 4 }, { 2.2, 3.3, -4.2, 6.0}),
factory.createArray<bool>({ 1, 4 }, { true, true, false, true }),
factory.createScalar<int32_t>(-3374)
);
Modify the array by overwriting the value in the cell referred to in MATLAB as C{1,1}.
Get a reference to the cell containing the double array and change the first element to -2.2.
Display the new values in the cell containing the double array:
See Also
matlab::data::ArrayFactory
Related Examples
• “Access C++ Data Array Container Elements” on page 2-6
2-5
2 External Data Interface (EDI)
Modify By Reference
To modify data in place, use a reference to the container element that you want to modify. For
example, this code modifies the values of the first cell in the CellArray object. The first cell is a 1-
by-3 logical array.
using namespace matlab::data;
ArrayFactory f;
After running this code, the first element of the cell array is a 1-by-3 logical array with each element
set to false.
For example, this code creates a copy of the last cell in the CellArray, which is a 1-by-3 double
array. The copy is modified by setting the first element in the double array to the numeric value 5.5.
After this modification, the value in the CellArray is unchanged and the copy is no longer a shared
value.
using namespace matlab::data;
ArrayFactory f;
2-6
Access C++ Data Array Container Elements
See Also
Related Examples
• “C++ Cell Arrays” on page 2-5
2-7
2 External Data Interface (EDI)
The apply_visitor and apply_visitor_ref functions dispatch to the operations defined by the
visitor class based on input array type. The visitor class defines operations to perform on specific
types of array.
• There are many operations that you need to perform on an array and the way to perform them
depends on the type of the array.
• The array returned by a function can be of different known types and you want to handle all cases.
• You are working with heterogeneous structures like cell arrays or structure arrays.
The apply_visitor_ref function dispatches to the visitor class operation based on the type of the
array reference passed as an input. The syntax for calling apply_visitor_ref accepts a
matlab::data::ArrayRef and your visitor class instance:
Overloading operator()
Implement your visitor class to overload the operator operator() for the array types you want to
operate on. For example, suppose one operation that you want to implement is to return the text
contained in a matlab::data::CharArray as a std::string. Implement the operation like this:
As another example, suppose that you want to negate the logical values in a
matlab::data::TypedArray. In this case, use a reference to the array:
You must use an element reference in the range-based for loop to change the value in the array.
2-8
Operate on C++ Arrays Using Visitor Pattern
The DisplayVisitor class implements operations to display the contents of cell arrays for arrays of
types bool, double, and char, and contained cell arrays. You can add new operations to support
other cell array contents by adding more overloaded functions.
type DisplayVisitor.cpp
#include "MatlabDataArray.hpp"
#include <iostream>
class DisplayVisitor {
public:
template <typename U>
void operator()(U arr) {}
2-9
2 External Data Interface (EDI)
type callDisplayCell.cpp
int main() {
ArrayFactory factory;
// Call function
DisplayCell(cellArray);
return 0;
}
The ModifyCell function calls apply_visitor_ref in a loop for each element in the cell array.
Because the objective is to modify the contents of the cell array, this example uses references to the
cell array contents.
type CellModifyVisitor.cpp
#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
class CellModifyVisitor {
public:
template <typename U>
void operator()(U arr) {}
2-10
Operate on C++ Arrays Using Visitor Pattern
};
type callModifyCell.cpp
int main() {
ArrayFactory factory;
// Call function
ModifyCell(cellArray);
return 0;
}
See Also
matlab::data::apply_visitor | matlab::data::apply_visitor_ref
Related Examples
• “C++ Cell Arrays” on page 2-5
2-11
2 External Data Interface (EDI)
In this section...
“matlab::data::CanOnlyUseOneStringIndexException” on page 2-12
“matlab::data::CantAssignArrayToThisArrayException” on page 2-12
“matlab::data::CantIndexIntoEmptyArrayException” on page 2-13
“matlab::data::DuplicateFieldNameInStructArrayException” on page 2-13
“matlab::data::FailedToLoadLibMatlabDataArrayException” on page 2-13
“matlab::data::FailedToResolveSymbolException” on page 2-13
“matlab::data::InvalidArrayIndexException” on page 2-13
“matlab::data::InvalidDimensionsInSparseArrayException” on page 2-13
“matlab::data::InvalidFieldNameException” on page 2-13
“matlab::data::MustSpecifyClassNameException” on page 2-13
“matlab::data::NonAsciiCharInRequestedAsciiOutputException” on page 2-13
“matlab::data::NonAsciiCharInInputDataException” on page 2-13
“matlab::data::InvalidArrayTypeException” on page 2-14
“matlab::data::NotEnoughIndicesProvidedException” on page 2-14
“matlab::data::StringIndexMustBeLastException” on page 2-14
“matlab::data::StringIndexNotValidException” on page 2-14
“matlab::data::SystemErrorException” on page 2-14
“matlab::data::TooManyIndicesProvidedException” on page 2-14
“matlab::data::TypeMismatchException” on page 2-14
“matlab::data::WrongNumberOfEnumsSuppliedException” on page 2-14
“matlab::data::InvalidMemoryLayoutException” on page 2-14
“matlab::data::InvalidDimensionsInRowMajorArrayException” on page 2-14
“matlab::data::NumberOfElementsExceedsMaximumException” on page 2-14
“matlab::data::ObjectArrayIncompatibleTypesException” on page 2-15
“matlab::data::AccessingObjectNotSupportedException” on page 2-15
“matlab::data::InvalidNumberOfElementsProvidedException” on page 2-15
“matlab::data::FeatureNotSupportedException” on page 2-15
matlab::data::CanOnlyUseOneStringIndexException
The CanOnlyUseOneStringIndexException exception occurs if more than one string index is
provided.
matlab::data::CantAssignArrayToThisArrayException
The CantAssignArrayToThisArrayException exception occurs if assigning an array to this array
is not supported.
2-12
MATLAB Data API Exceptions
matlab::data::CantIndexIntoEmptyArrayException
The CantIndexIntoEmptyArrayException exception occurs when attempting any indexing
operation on an empty array.
matlab::data::DuplicateFieldNameInStructArrayException
The DuplicateFieldNameInStructArrayException exception occurs if a duplicate field name is
encountered in a struct definition.
matlab::data::FailedToLoadLibMatlabDataArrayException
The FailedToLoadLibMatlabDataArrayException exception occurs if necessary MATLAB Data
Array libraries failed to load.
matlab::data::FailedToResolveSymbolException
The FailedToResolveSymbolException exception occurs if unable to resolve a required symbol
in the MATLAB Data Array libraries.
matlab::data::InvalidArrayIndexException
The InvalidArrayIndexException exception occurs if the index provided is not valid for the array
being indexed.
matlab::data::InvalidDimensionsInSparseArrayException
The InvalidDimensionsInSparseArrayException exception occurs if the caller attempts to
create a sparse array with more than two dimensions.
matlab::data::InvalidFieldNameException
The InvalidFieldNameException exception occurs if field name is invalid for a struct.
matlab::data::MustSpecifyClassNameException
The MustSpecifyClassNameException exception occurs if class name is not specified.
matlab::data::NonAsciiCharInRequestedAsciiOutputException
The NonAsciiCharInRequestedAsciiOutputException exception occurs if user attempts to
create a CharArray or a StringArray with a std::string and the std::string contains non-
ASCII characters.
matlab::data::NonAsciiCharInInputDataException
The NonAsciiCharInInputDataException exception occurs if user attempts to create a
CharArray or a StringArray with a std::string and the std::string contains non-ASCII
characters.
2-13
2 External Data Interface (EDI)
matlab::data::InvalidArrayTypeException
The InvalidArrayTypeException exception occurs if the type of rhs does not match the type of
TypedArray<T>.
matlab::data::NotEnoughIndicesProvidedException
The NotEnoughIndicesProvidedException exception occurs if not enough indices are provided.
matlab::data::StringIndexMustBeLastException
The StringIndexMustBeLastException exception occurs if a string index is not the last index.
matlab::data::StringIndexNotValidException
The StringIndexNotValidException exception occurs if a string index is not valid for this array.
matlab::data::SystemErrorException
The SystemErrorException exception occurs if a system error occurs.
matlab::data::TooManyIndicesProvidedException
The TooManyIndicesProvidedException exception occurs if too many indices are provided.
matlab::data::TypeMismatchException
The TypeMismatchException exception occurs if the element of the Array does not contain T's.
matlab::data::WrongNumberOfEnumsSuppliedException
The WrongNumberOfEnumsSuppliedException exception occurs if the wrong number of enums is
provided.
matlab::data::InvalidMemoryLayoutException
The InvalidMemoryLayoutException exception occurs if you try to add a row-major array to a
column-major buffer or vice versa.
matlab::data::InvalidDimensionsInRowMajorArrayException
The InvalidDimensionsInRowMajorArrayException exception occurs for arrays created with
MATLAB R2019a and R2019b if a row-major array is not 2-D.
matlab::data::NumberOfElementsExceedsMaximumException
The NumberOfElementsExceedsMaximumException exception occurs if the number of elements is
greater than size_t.
2-14
MATLAB Data API Exceptions
matlab::data::ObjectArrayIncompatibleTypesException
The ObjectArrayIncompatibleTypesException exception occurs if you try to combine elements
of a matlab::data::ObjectArray into a heterogeneous array.
matlab::data::AccessingObjectNotSupportedException
If the class defining an Object in a matlab::data::ObjectArray overrides subsref or
subsasgn, then you cannot access the elements of the ObjectArray. The
AccessingObjectNotSupportedException exception occurs when you try to access these
elements.
matlab::data::InvalidNumberOfElementsProvidedException
The InvalidNumberOfElementsProvidedException exception occurs if you do not provide the
required number of elements to initialize a matlab::data::ObjectArray.
matlab::data::FeatureNotSupportedException
The FeatureNotSupportedException exception occurs when interacting with a version of
MATLAB that does not support row-major arrays.
See Also
2-15
2 External Data Interface (EDI)
matlab::data::ArrayDimensions
ArrayDimensions is defined as std::vector<size_t> in the ArrayDimensions.hpp header
file.
matlab::data::Enumeration
Enumeration is defined in the Enumeration.hpp header file.
matlab::data::MATLABString
MATLABString is defined as optional<String> in the String.hpp header file.
matlab::data::ObjectArray
ObjectArray is defined as TypedArray<Object> in the ObjectArray.hpp header file.
matlab::data::String
String is defined as std::basic_string<uchar> in the String.hpp header file.
matlab::data::Struct
Struct is defined in the Struct.hpp header file.
2-16
MATLAB Data API Types
Use get() to access the data. Do not call release(). For an example, see “Pass Sparse Arrays to
MATLAB From C++” on page 14-41.
iterator
iterator is defined as TypedIterator<T> in the TypedArray.hpp header file.
const_iterator
const_iterator is defined as TypedIterator<typename std::add_const<T>::type> in the
TypedArray.hpp header file.
reference
reference is defined in the TypedArray.hpp header file as typename iterator::reference,
where iterator::reference is T& for arithmetic types and Reference<T> for non-arithmetic
types.
const_reference
const_reference is defined in the TypedArray.hpp header file as typename
const_iterator::reference, where const_iterator::reference is T& for arithmetic types
and Reference<T> for non-arithmetic types.
Reference Types
• ArrayRef is defined as Reference<Array> in the TypedArrayRef.hpp header file.
• CellArrayRef is defined as Reference<TypedArray<Array>> in the TypedArrayRef.hpp
header file.
• CharArrayRef is defined as TypedArrayRef<CHAR16_T> in the CharArray.hpp header file.
• EnumArrayRef is defined as TypedArrayRef<Enumeration> in the EnumArray.hpp header
file.
• SparseArrayRef is defined as Reference<SparseArray<T>> in the SparseArrayRef.hpp
header file.
• StructArrayRef is defined as Reference<TypedArray<Struct>> in the
TypedArrayRef.hpp header file.
• TypedArrayRef is defined as Reference<TypedArray<T>> in the TypedArrayRef.hpp
header file.
2-17
3
• Access Java class packages that support activities such as I/O and networking.
• Access third party Java classes.
• Construct Java objects in MATLAB workspace.
• Call Java object methods, using either Java or MATLAB syntax.
• Pass data between MATLAB variables and Java objects.
To find out which version of JVM software MATLAB uses on your platform, type the following at the
MATLAB prompt:
version -java
For information about JVM support, see MATLAB Supported Language Interfaces.
See Also
Related Examples
• “Call Java Method” on page 3-3
External Websites
• MATLAB Supported Language Interfaces
3-2
Call Java Method
The java.util.ArrayList class is part of the Java standard libraries. Therefore, the class is
already on the Java class path. If you call a method in a class that is not in a standard library, then
update the Java class path so that MATLAB can find the method. For information, see “Java Class
Path” on page 3-7.
methodsview('java.util.ArrayList')
ArrayList (java.util.Collection)
ArrayList ( )
ArrayList (int)
Choose the ArrayList() syntax, which constructs an empty list with an initial capacity of 10.
import java.util.ArrayList
A = ArrayList;
3-3
3 Using Java Libraries from MATLAB
add(A,5);
A
A =
[5.0]
A =
[5.0, 10.0]
B is a reference to A. Any change to the object referenced by B also changes the object at A. Either
MATLAB code or Java code can change the object. For example, add a value to B, and then display A.
add(B,15);
A
A =
ans =
'java.util.ArrayList'
A =
To use A in MATLAB, convert the object to either a java.lang.Object type or to a primitive type.
Then apply the MATLAB cell and cell2mat functions.
From the ArrayList methods window, find the toArray method that converts an ArrayList to
java.lang.Object[].
java.lang.Object[] toArray (java.lang.Object[])
Convert A to java.lang.Object.
3-4
Call Java Method
res = toArray(A)
res =
java.lang.Object[]:
[ 5]
[10]
[15]
res = cell(res)'
res =
To convert this value to a matrix, the elements must be the same type. In this example, the values
convert to type double.
data = cell2mat(res)
data =
5 10 15
See Also
import | javaMethod
Related Examples
• “Call Method in Your Own Java Class” on page 3-16
More About
• “Java Class Path” on page 3-7
• “Pass Data to Java Methods” on page 3-46
• “Handle Data Returned from Java Methods” on page 3-51
• “How MATLAB Allocates Memory”
External Websites
• https://docs.oracle.com/javase/7/docs/api/overview-summary.html
3-5
3 Using Java Libraries from MATLAB
• java.lang.String
• java.util.Enumeration
A fully qualified name can be long, making commands and functions (such as constructors)
cumbersome to edit and to read. To refer to classes by the class name alone (without a package
name), first import the fully qualified name into MATLAB.
MATLAB adds all classes that you import to a list called the import list. To see what classes are on
that list, type import. Your code can refer to any class on the list by class name alone.
When called from a function, import adds the specified classes to the import list in effect for that
function. When invoked at the command prompt, import uses the base import list for your MATLAB
platform.
import java.lang.String
import java.util.* java.awt.*
import java.util.Enumeration
The following statements refer to the String, Frame, and Enumeration classes without using the
package names.
clear import
See Also
import
Related Examples
• “Call Java Method” on page 3-3
3-6
Java Class Path
Built-in Java class packages—classes in the Java standard libraries—are already on the class path. You
do not need to modify the path to access these classes.
To access Java classes from MATLAB, add them to the class path. For information and examples, see
“Static Path of Java Class Path” on page 3-9.
MATLAB segments the Java class path into a static path and a dynamic path. MATLAB searches the
static path before the dynamic path.
• Use the static path as the default path to load a Java class.
• Use the dynamic path when developing your own Java classes. You can modify and load the
dynamic path any time during a MATLAB session.
See Also
javaclasspath
Related Examples
• “Call Java Method” on page 3-3
• “Call Method in Your Own Java Class” on page 3-16
More About
• “Static Path of Java Class Path” on page 3-9
• “Dynamic Path of Java Class Path” on page 3-15
3-7
3 Using Java Libraries from MATLAB
3-8
Static Path of Java Class Path
To add files to the static Java class path, create a javaclasspath.txt file. For instructions, see
“Create javaclasspath.txt File” on page 3-9.
For convenience when developing your own Java classes, add entries to the dynamic Java class path.
For information, see “Dynamic Path of Java Class Path” on page 3-15.
For more information about how MATLAB uses the class path, see “Java Class Path” on page 3-7.
• For classes defined in Java packages, see “Add Packages” on page 3-10.
• For classes defined in individual .class files, see “Add Individual (Unpackaged) Classes” on
page 3-10.
• For classes defined in Java Archive (JAR) files, see “Add JAR File Classes” on page 3-10.
3 Simplify folder specifications in cross-platform environments by using the $matlabroot, $arch,
and $jre_home macros.
4 Save the file in your preferences folder. To view the location of the preferences folder, type:
prefdir
Alternatively, save the javaclasspath.txt file in your MATLAB startup folder. To identify the
startup folder, type pwd at the command line immediately after starting MATLAB. Classes
specified in the javaclasspath.txt file in the startup folder appear on the path before classes
specified in the file in the preferences folder. If a class appears in more than one folder or jar file,
then Java uses the first one it finds.
5 Restart MATLAB.
MATLAB reads the static class path only at startup. If you edit javaclasspath.txt or change
your .class files while MATLAB is running, then restart MATLAB to put those changes into effect.
If you do not want MATLAB to use the entries in the javaclasspath.txt file, then start MATLAB
with the -nouserjavapath option.
For information about using the dynamic class path when writing your own Java classes, see
“Dynamic Path of Java Class Path” on page 3-15. For information about the startup folder, see
“MATLAB Startup Folder”.
3-9
3 Using Java Libraries from MATLAB
c:\work\javaclasses
Add Packages
To make a package available to MATLAB, specify the full path to the parent folder of the highest level
folder of the package path. This folder is the first component in the package name. For example, if
your Java class package com.mw.tbx.ini has its classes in folder c:\work\com\mw\tbx\ini, add
the following entry to the javaclasspath.txt file.
c:\work
To make the contents of a JAR file available for use in MATLAB, specify the full path, including the full
file name, for the JAR file. You also can put the JAR file on the MATLAB path.
Note The path requirement for JAR files is different from the requirement for .class files and
packages, for which you do not specify file names.
For example, you have a JAR file named mylibrary.jar in the folder C:\Documents\MATLAB\,
containing a method, package.class.mymethod(params).
cd(prefdir)
edit javaclasspath.txt
• Add the following text on a new line in the file.
C:\Documents\MATLAB\mylibrary.jar
• Save and close the file.
• Restart MATLAB.
• Call mymethod.
package.class.mymethod(params)
See Also
More About
• “Java Class Path” on page 3-7
3-10
Static Path of Java Class Path
External Websites
• Java™ Platform, Standard Edition 7 API Specification
3-11
3 Using Java Libraries from MATLAB
[~,~,j] = inmem;
j
j =
'java.util.Date'
'com.mathworks.ide.desktop.MLDesktop'
Note When you call the which function on methods defined by Java classes, the function only
displays the classes currently loaded into the MATLAB workspace. In contrast, which displays
MATLAB classes, whether or not they are loaded.
See Also
inmem
3-12
Locate Native Method Libraries
You can augment the search path for native method libraries by creating an ASCII text file named
javalibrarypath.txt in your preferences folder. Follow these guidelines when editing this file.
cd(prefdir)
edit javalibrarypath.txt
• Specify each new folder on a line by itself.
• Specify only the folder names, not the names of the DLL files. The System.loadLibrary call
reads the file names.
• In cross-platform environments, simplify the specification of folders by using the $matlabroot,
$arch, and $jre_home macros.
You also can create a javalibrarypath.txt file in your MATLAB startup folder. To identify the
startup folder, type pwd at the command line immediately after starting MATLAB. Libraries specified
in the javalibrarypath.txt file in the startup folder override libraries specified in the file in the
preferences folder.
To disable using the javalibrarypath.txt file, start MATLAB with the -nouserjavapath option.
See Also
prefdir
More About
• “MATLAB Startup Folder”
3-13
3 Using Java Libraries from MATLAB
java.lang.Class.forName('xyz.myapp.MyClass')
with:
javaObjectEDT('xyz.myapp.MyClass')
See Also
javaObjectEDT
3-14
Dynamic Path of Java Class Path
MATLAB provides the dynamic path as a convenience for when you develop your own Java classes.
You can change class definitions on the dynamic path without restarting MATLAB. Therefore, it is
useful to put a user-defined Java class definition on the dynamic path while you develop and debug
the class.
While the dynamic path offers greater flexibility in changing the path, Java classes on the dynamic
path might load more slowly than classes on the static path. Also, classes on the dynamic path might
not behave identically to classes on the static path. If your class does not behave as expected, then
use the static path.
After developing a Java class, put the class on the static path. For more information, see “Static Path
of Java Class Path” on page 3-9
To add a class to the dynamic path, use the javaclasspath and javaaddpath functions. To remove
an entry, use the javarmpath function. These functions clear all existing variables and global
variables in the workspace.
Note Do not put Java classes on the static path if they have dependencies on classes on the dynamic
path.
See Also
javaclasspath | javaaddpath | javarmpath
More About
• “Static Path of Java Class Path” on page 3-9
3-15
3 Using Java Libraries from MATLAB
After you create class definitions in .java files, use your Java compiler to produce .class files. The
next step is to make the class definitions in those .class files available for you to use in MATLAB.
This example shows how to call a method in your own Java class. The example uses a class file named
myclass.class in the folder C:\Documents\MATLAB\ containing a method
package.myclass.mymethod(params).
Put the class file on the dynamic Java class path, making the class available in the current MATLAB
session only. MATLAB provides the dynamic path as a convenience for when you develop your own
Java classes.
• Add the class to the dynamic Java class path. To access the class, you must modify the Java path
every time you start MATLAB.
javaaddpath('C:\Documents\MATLAB\')
• Call the method. Substitute your own class file name and path, and call the method with the
appropriate parameter list.
package.myclass.mymethod(params)
• Make the class always available in MATLAB. Add it to the static class path by editing the
javaclasspath.txt file in your prefdir folder.
See Also
javaaddpath
More About
• “Dynamic Path of Java Class Path” on page 3-15
• “Static Path of Java Class Path” on page 3-9
External Websites
• MATLAB Supported Language Interfaces
3-16
How MATLAB Represents Java Arrays
The term dimension refers to the number of subscripts required to address the elements of an array.
Dimension is not a measure of length, width, and height. For example, a 5-by-1 array is one-
dimensional, because you use one subscript to access an individual element. To work with a two-
dimensional array, create an array of arrays. To add further dimensions, add more levels to the array,
making it an array of arrays of arrays, and so on.
MATLAB treats multilevel Java arrays like matrices and multidimensional arrays. Use the same
MATLAB syntax to access elements of a Java array.
Array Indexing
Java array indices are zero-based while MATLAB array indices are one-based. In Java programming,
you access the elements of array y of length N using y[0] through y[N-1]. When working with this
array in MATLAB, you access these elements using y(1) through y(N).
This image shows an array of three underlying arrays of different lengths. The term jagged (or
ragged) is commonly used to describe this arrangement of array elements as the array ends do not
match up evenly. When a Java method returns a jagged array of primitive Java types, MATLAB stores
it in a cell array.
The MATLAB string function pads a jagged Java string array, making it a rectangular MATLAB
array.
The potentially ragged shape of a Java array makes it impossible to size the array in the same way as
for a MATLAB array. In a Java array, no single value represents the size of the lower-level arrays.
3-17
3 Using Java Libraries from MATLAB
size(A) returns the dimensions of the highest array level of A. The highest level of the array has a
size of 3-by-1.
size(A)
ans =
3 1
To find the size of a lower-level array, for example the five-element array in row 3, refer to the row
explicitly.
size(A(3))
ans =
5 1
You can specify a dimension in the size command using the following syntax. However, this
command only sizes the first dimension, dim=1, the only nonunary dimension.
m = size(X,dim)
size(A,1)
ans =
3
See Also
size | ndims
3-18
Create Array of Java Objects
To create a Java object array, use the MATLAB javaArray function. For example, the following
command creates a Java array of four lower-level arrays, each containing five objects of the
java.lang.Double class.
dblArray = javaArray('java.lang.Double',4,5);
The javaArray function does not initialize values in the array. This code copies the first four rows of
MATLAB array A, containing randomly generated data, into dblArray.
A = rand(5);
for m = 1:4
for n = 1:5
dblArray(m,n) = java.lang.Double(A(m,n));
end
end
dblArray
dblArray =
java.lang.Double[][]:
You must convert each element of A to the java.lang.Double type. For more information, see “Pass
Java Objects” on page 3-48.
For example, create a java.awt.Polygon by looking at the constructors in the following methods
window.
methodsview('java.awt.Polygon')
Polygon (int[],int[],int)
MATLAB converts a MATLAB double to a Java scalar or array int. Create two MATLAB arrays,
identifying four points of a polygon.
3-19
3 Using Java Libraries from MATLAB
To call the Polygon object method contains, look at its signature in the method window.
MATLAB converts a MATLAB double to a Java double. This statement checks if the point (50,40) is
within the polygon.
contains(polygon,50,40)
ans =
logical
See Also
javaArray
More About
• “Pass Java Objects” on page 3-48
• “MATLAB Type to Java Type Mapping” on page 3-46
3-20
Access Elements of Java Array
matlabArr =
11 12 13 14 15
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45
javaArr =
java.lang.Integer[][]:
ans = 31
3-21
3 Using Java Libraries from MATLAB
ans =
java.lang.Integer[]:
[31]
[32]
[33]
[34]
[35]
Linear indexing into a Java array enables you to specify an entire array from a larger array structure.
Then you can manipulate it as an object.
dblArray = javaArray('java.lang.Double',4,5);
for m = 1:4
for n = 1:5
dblArray(m,n) = java.lang.Double((m*10)+n);
end
end
dblArray
dblArray =
java.lang.Double[][]:
row2Array = dblArray(2,2:4)
row2Array =
java.lang.Double[]:
[22]
[23]
[24]
You also can use the colon with linear indexing to refer to all elements in the entire matrix. However,
Java and MATLAB arrays are stored differently in memory meaning that the order of the elements in a
linear array is different. Java array elements are stored in a row-by-column format, an order that
matches the rows of the matrix. MATLAB array elements are stored column-wise, an order that
matches the columns. For example, convert the 4-by-5 array dblArray into a 20-by-1 linear array.
linearArray = dblArray(:)
linearArray =
3-22
Access Elements of Java Array
java.lang.Double[]:
[11]
[12]
[13]
[14]
[15]
[21]
[22]
[23]
[24]
[25]
[31]
[32]
[33]
[34]
[35]
[41]
[42]
[43]
[44]
[45]
last2rows = dblArray(3:end,:)
last2rows =
java.lang.Double[][]:
Do not use end on lower-level arrays. Because of the potentially ragged nature of the arrays,
MATLAB cannot determine the end value. For more information, see “Shape of Java Arrays” on page
3-17.
3-23
3 Using Java Libraries from MATLAB
See Also
More About
• “Shape of Java Arrays” on page 3-17
• “java.lang.Object Return Types” on page 3-51
• “Array Indexing”
3-24
Assign Values to Java Array
A(row,column) = java.lang.Double(value)
In a Java program, you would assign the value to A[row-1][column-1]. For more information on
the differences between Java and MATLAB arrays, see “How MATLAB Represents Java Arrays” on
page 3-17.
To run the examples in this topic, create a 4-by-5 array dblArray. The values displayed for
dblArray depend on the order in which you run the examples.
dblArray = javaArray('java.lang.Double',4,5);
for m = 1:4
for n = 1:5
dblArray(m,n) = java.lang.Double((m*10)+n);
end
end
dblArray
dblArray =
java.lang.Double[][]:
onedimArray = javaArray('java.lang.Double',5);
for k = 1:5
onedimArray(k) = java.lang.Double(100*k);
end
dblArray(3) = onedimArray
dblArray =
java.lang.Double[][]:
3-25
3 Using Java Libraries from MATLAB
dblArray(:) = java.lang.Double(0)
dblArray =
java.lang.Double[][]:
Use the colon operator as you would when working with MATLAB arrays. For example, assign one
value to each row in dblArray.
dblArray(1,:) = java.lang.Double(125);
dblArray(2,:) = java.lang.Double(250);
dblArray(3,:) = java.lang.Double(375);
dblArray(4,:) = java.lang.Double(500)
dblArray =
java.lang.Double[][]:
dblArray(2,2) = []
dblArray =
java.lang.Double[][]:
Subscripted Deletion
If you assign an empty matrix to an entire row or column of a MATLAB array, then MATLAB removes
that row or column from the array. When you assign the empty matrix to a Java array, the array
maintains its dimensions.
3-26
Assign Values to Java Array
for m = 1:4
for n = 1:5
matlabArr(m,n) = (m*10) + n;
end
end
matlabArr
matlabArr =
11 12 13 14 15
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45
Assign the empty matrix to the fourth column. This statement changes its dimensions from 4-by-5 to
4-by-4.
matlabArr(:,4) = []
matlabArr =
11 12 13 15
21 22 23 25
31 32 33 35
41 42 43 45
When you assign the empty matrix to the Java array dblArray, the array maintains its 4-by-5
dimensions.
dblArray(:,4) = []
dblArray =
java.lang.Double[][]:
3-27
3 Using Java Libraries from MATLAB
You can concatenate Java objects only along the first (vertical) or second (horizontal) axis. For more
information, see “How MATLAB Represents Java Arrays” on page 3-17.
d1 =
java.lang.Double[][]:
d2 = javaArray('java.lang.Double',2,2);
for m = 1:2
for n = 1:3
d2(m,n) = java.lang.Double((n+3)*2 + m-1);
end
end
d2
d2 =
java.lang.Double[][]:
d3 =
java.lang.Double[][]:
Vector Concatenation
This example shows the difference between row and column concatenation for vectors. Create two
vectors J1 and J2.
3-28
Concatenate Java Arrays
import java.lang.Integer
J1 = [];
for ii = 1:3
J1 = [J1;Integer(ii)];
end
J1
J1 =
java.lang.Integer[]:
[1]
[2]
[3]
J2 = [];
for ii = 4:6
J2 = [J2;Integer(ii)];
end
J2
J2 =
java.lang.Integer[]:
[4]
[5]
[6]
Concatenate by column. Horizontally concatenating two Java vectors creates a longer vector, which
prints as a column.
Jh = [J1,J2]
Jh =
java.lang.Integer[]:
[1]
[2]
[3]
[4]
[5]
[6]
Concatenate by row. Vertically concatenating two Java vectors creates a 2-D Java array.
Jv = [J1;J2]
Jv =
java.lang.Integer[][]:
Note Unlike MATLAB, a 3x1 Java array is not the same as a Java vector of length 3. Create a 3x1
array.
3-29
3 Using Java Libraries from MATLAB
import java.lang.Integer
arr1 = javaArray('java.lang.Integer',3,1)
arr1 =
java.lang.Integer[][]:
[]
[]
[]
arr2 = javaArray('java.lang.Integer',3)
arr2 =
java.lang.Integer[]:
[]
[]
[]
See Also
More About
• “Construct and Concatenate Java Objects” on page 3-34
• “Creating, Concatenating, and Expanding Matrices”
• “How MATLAB Represents Java Arrays” on page 3-17
3-30
Create Java Array References
origArray = javaArray('java.lang.Double',3,4);
for m = 1:3
for n = 1:4
origArray(m,n) = java.lang.Double((m*10)+n);
end
end
origArray
origArray =
java.lang.Double[][]:
newArrayRef = origArray;
Change the array referred by newArrayRef. The changes also show up in origArray.
newArrayRef(3,:) = java.lang.Double(0);
origArray
origArray =
java.lang.Double[][]:
See Also
Related Examples
• “Create Copy of Java Array” on page 3-32
3-31
3 Using Java Libraries from MATLAB
origArray = javaArray('java.lang.Double',3,4);
for m = 1:3
for n = 1:4
origArray(m,n) = java.lang.Double((m*10)+n);
end
end
origArray
origArray =
java.lang.Double[][]:
newArray = origArray(:,:)
newArray =
java.lang.Double[][]:
newArray(3,:) = java.lang.Double(0)
newArray =
java.lang.Double[][]:
origArray
origArray =
java.lang.Double[][]:
3-32
Create Copy of Java Array
See Also
Related Examples
• “Create Java Array References” on page 3-31
3-33
3 Using Java Libraries from MATLAB
Java objects are not arrays like MATLAB types. Calling MATLAB functions that expect MATLAB arrays
might have unexpected results. Use Java methods to work on Java arrays instead. For an example, see
“Call Java Method” on page 3-3.
Concatenating objects of the same Java class results in an array of objects of that class.
value1 = java.lang.Integer(88);
value2 = java.lang.Integer(45);
cat(1,value1,value2)
ans =
java.lang.Integer[]:
[88]
[45]
byte = java.lang.Byte(127);
integer = java.lang.Integer(52);
double = java.lang.Double(7.8);
[byte integer double]
ans =
java.lang.Number[]:
[ 127]
[ 52]
[7.8000]
byte = java.lang.Byte(127);
point = java.awt.Point(24,127);
[byte point]
3-34
Construct and Concatenate Java Objects
ans =
java.lang.Object[]:
[ 127]
[1×1 java.awt.Point]
See Also
Related Examples
• “Call Java Method” on page 3-3
3-35
3 Using Java Libraries from MATLAB
When you save or load a Java object, the object and its class must meet all this criteria:
• The class implements the Java API Serializable interface, either directly or by inheriting it
from a parent class. Any embedded or otherwise referenced objects also must implement
Serializable.
• Do not change the class definition between saving and loading the object. Changes to the data
fields or methods of a class prevent the loading of an object that was constructed with another
class definition.
• Values in transient data fields are not saved with the object. Either the class does not have any
transient data fields, or the values are not significant.
If you define your own Java classes, or subclasses of existing classes, follow the same criteria to
enable saving and loading objects of the class in MATLAB. For details on defining classes to support
serialization, consult your Java development documentation.
See Also
save | load
3-36
Data Fields of Java Objects
To access public data fields, which your code can read or modify directly, use the syntax:
object.field
To read from and, where allowed, to modify private data fields, use the accessor methods defined by
the Java class. These methods are sometimes referred to as get and set methods.
For example, the java.awt.Frame class has both private and public data fields. The read accessor
method getSize returns a java.awt.Dimension object.
frame = java.awt.Frame;
frameDim = getSize(frame)
frameDim =
java.awt.Dimension[width=0,height=0]
The Dimension class has public data fields height and width. Display the value of height.
height = frameDim.height
height = 0
frameDim =
java.awt.Dimension[width=42,height=0]
ans =
'MIN_VALUE'
'MAX_VALUE'
'TYPE'
'SIZE'
ans =
'static final int MIN_VALUE'
3-37
3 Using Java Libraries from MATLAB
thisType = java.lang.Integer.TYPE
thisType =
int
value = java.lang.Integer(0);
thatType = value.TYPE
thatType =
int
MATLAB does not allow assignment to static fields using the class name. To assign a value, use the
static set method of the class or create an instance of the class. For example, assign value to the
following staticFieldName field by creating an instance of java.className.
objectName = java.className;
objectName.staticFieldName = value;
See Also
fieldnames
3-38
Determine Class of Java Object
value = java.lang.Integer(0);
myClass = class(value)
myClass = java.lang.Integer
The class function does not tell you whether the class is a Java class. For this information, call the
isjava function. For example, the class value is a Java class:
isjava(value)
ans =
1
To find out if an object is an instance of a specific class, call the isa function. The class can be a
MATLAB built-in, a user-defined class, or a Java class. For example:
isa(value,'java.lang.Integer')
ans =
1
See Also
class | isjava | isa
3-39
3 Using Java Libraries from MATLAB
Method Information
To return the names of all the methods (including inherited methods) of the class, use methods
without the '-full' qualifier. Names of overloaded methods are listed only once.
For example, display a full description of all methods of the java.awt.Dimension object.
methodsview java.awt.MenuItem
A new window appears, listing one row of information for each method in the class. Each row in the
window displays these fields of information describing the method.
3-40
Method Information
See Also
methods | methodsview
3-41
3 Using Java Libraries from MATLAB
For example, to find the package and class name for the concat method, type:
which concat
Suppose that you loaded the Java String and java.awt.Frame classes. Both of these classes have
an equals method. Type:
The which function operates differently on Java classes than it does on MATLAB classes:
You can find out which Java classes are currently loaded by using the command [m,x,j]=inmem.
See Also
which | inmem
More About
• “Load Java Class Definitions” on page 3-12
• “Java Class Path” on page 3-7
3-42
Java Methods That Affect MATLAB Commands
When calling disp on a Java object, MATLAB formats the output using the object toString method.
If the class does not implement this method, then MATLAB uses an inherited toString method. If no
intermediate ancestor classes define this method, MATLAB uses the toString method defined by the
java.lang.Object class.
To change the way MATLAB displays an object, implement your own toString method in your class
definition.
When you compare two Java objects using isequal, MATLAB performs the comparison using the
Java method, equals. MATLAB first determines the class of the objects specified in the command,
and then uses the equals method implemented by that class. If equals is not implemented in this
class, then MATLAB uses an inherited equals method. If no intermediate ancestor classes define this
method, MATLAB uses the equals method defined by the java.lang.Object class.
To change the way MATLAB compares members of a class, implement your own equals method in
your class definition.
See Also
More About
• “Functions to Convert Java Objects to MATLAB Types” on page 3-52
3-43
3 Using Java Libraries from MATLAB
For example, MATLAB has a function named size, and the Java API java.awt.Frame class also has
a size method. If you call size on a Frame object, the size method defined by java.awt.Frame is
executed. However, if you call size on an object of java.lang.String, MATLAB does not find a
size method for this class. Therefore, it executes the MATLAB size function instead.
text = java.lang.String('hello');
size(text)
ans =
1 1
Note When you define a Java class for use in MATLAB, avoid giving any of its methods the same
name as a MATLAB function.
See Also
3-44
Avoid Calling Java main Methods in MATLAB
Be cautious when calling main methods from MATLAB, particularly main methods that start a user
interface. main methods are written assuming they are the entry point to application code. When
called from MATLAB, main is not the entry point, and the fact that other Java UI code might be
already running can lead to problems.
See Also
3-45
3 Using Java Libraries from MATLAB
Each row in the following table shows a MATLAB type followed by the possible Java argument
matches, from left to right in order of closeness of the match. The MATLAB types (except cell arrays)
can be scalar (1-by-1) arrays or matrices. The Java types can be scalar values or arrays.
3-46
Pass Data to Java Methods
In converting MATLAB to Java arrays, MATLAB handles dimension in a special manner. For a
MATLAB array, dimension is the number of nonsingleton dimensions in the array. For example, a 10-
by-1 array has dimension 1. Whereas, a 1-by-1 array has dimension 0 because you cannot index into a
scalar value. In Java code, the number of nested arrays determines the dimension. For example,
double[][] has dimension 2, and double has dimension 0.
If the number of dimensions of the Java array matches the number of dimensions in MATLAB array n,
then the converted Java array has n dimensions. If the Java array has fewer than n dimensions, then
the conversion drops singleton dimensions, starting with the first one. The conversion stops when the
number of remaining dimensions matches the number of dimensions in the Java array. If the Java
array has more than n dimensions, then MATLAB adds trailing singleton dimensions.
If the argument is a floating-point number, then MATLAB does not convert it to an integer in the same
manner as Java. MATLAB first converts a floating-point number to a 64-bit signed integer with the
fractional part truncated. Then the number is processed as if it were an int64 argument.
A floating-point number is too large to be represented in a 64-bit integer when it is (outside the range
from -263–263. In which case, MATLAB uses the following conversions:
3-47
3 Using Java Libraries from MATLAB
If the method argument is an array of type String, then pass a string array or a cell array of
character vectors. MATLAB converts the input to a Java array of String objects, with dimensions
adjusted as described in “How Array Dimensions Affect Conversion” on page 3-47.
Pass java.lang.Object
A special case exists when the method takes an argument of the java.lang.Object class. Since
this class is the root of the Java class hierarchy, you can pass objects of any class in the argument.
MATLAB automatically converts the argument to the closest Java Object type, which might include
Java-style autoboxing. This table shows the conversion.
3-48
Pass Data to Java Methods
To create a cell array of Java objects, use the MATLAB syntax {a1,a2,...}. You index into a cell
array of Java objects in the usual way, with the syntax a{m,n,...}. For example, create cell array A:
a1 = java.lang.Double(100);
a2 = java.lang.Float(200);
A = {a1,a2}
A =
• If the argument is an empty character vector and the parameter is declared as String, then
MATLAB passes in an empty (not null) Java String object.
• For all other cases, MATLAB converts an empty array to a Java null.
Overloaded Methods
When calling an overloaded method on a Java object, MATLAB compares the arguments you pass to
the arguments defined for the methods. In this context, the term method includes constructors.
MATLAB determines the method to call and converts the arguments to Java types according to the
Java conversion rules. For more information, see “Pass Array of Objects” on page 3-49.
If all these conditions are satisfied, then MATLAB calls the method.
In a call to an overloaded method, if there is more than one candidate, MATLAB selects the one with
arguments that best fit the calling arguments. First, MATLAB rejects methods that have argument
types incompatible with the passed arguments. For example, if the method has a double argument, a
char argument is incompatible.
3-49
3 Using Java Libraries from MATLAB
MATLAB then selects the method with the highest fitness value, which is the sum of the fitness values
of all its arguments. The fitness value for each argument is the fitness of the base type minus the
difference between the MATLAB array dimension and the Java array dimension. For information
about array dimensionality, see “How Array Dimensions Affect Conversion” on page 3-47. If two
methods have the same fitness, then the first one defined in the Java class is chosen.
See Also
More About
• “Handle Data Returned from Java Methods” on page 3-51
3-50
Handle Data Returned from Java Methods
If a Java method signature specifies a return data of type java.lang.Object, then MATLAB
converts the actual type returned, as shown in the table in “java.lang.Object Return Types” on page
3-51.
MATLAB does not convert other Java objects to MATLAB types. For information about handling this
data, see “Functions to Convert Java Objects to MATLAB Types” on page 3-52.
Example
Call the method on a String object. MATLAB converts the output to a char array.
str = java.lang.String('hello');
res = str.toCharArray'
res =
hello
3-51
3 Using Java Libraries from MATLAB
There is no conversion if the return argument is a subclass of Object or an array of Object. The
object remains a Java object. However, if you index into a returned Object array, MATLAB converts
the value according to the table. For more information, see “Converting Object Array Elements to
MATLAB Types” on page 3-23.
Example
java.lang.Object getData()
If getData returns a java.lang.Integer object, then MATLAB converts the value to double.
java.lang.Object getData()
But MATLAB does not convert the return value for this method:
java.lang.String getData()
To convert Java object data to MATLAB data, use MATLAB functions as described in these topics:
To convert Java numeric types to MATLAB types, use a numeric MATLAB function like double. The
action taken by the double function depends on the class of the object you specify.
• If the object is an instance of a class derived from java.lang.Number, then MATLAB converts
the object to a MATLAB double.
3-52
Handle Data Returned from Java Methods
• If the object is not an instance of a numeric class, then MATLAB checks the class definition for a
toDouble method. MATLAB calls this method to perform the conversion.
• If you create your own class, then write a toDouble method to specify your own type conversion.
Note If the class of the object is not derived from java.lang.Number and it does not implement a
toDouble method, then the double function displays an error message.
To convert java.lang.String objects and arrays to MATLAB strings or character vectors, use the
MATLAB string or char function.
If the object specified in the MATLAB function is not an instance of the java.lang.String class,
then MATLAB checks its class definition for a toString or a toChar method. If you create your own
class, then write a toString or toChar method to specify the string conversion.
Note If the class of the object is not java.lang.String and it does not implement a toChar
method, then the char function displays an error message.
If a Java class defines field names, then use the struct function to convert the object data to a
MATLAB structure.
Suppose that you call a Java method that returns a java.awt.Polygon object. The class defines
fields xpoints and ypoints. To run this example, create a polygon variable.
polygon = java.awt.Polygon([14 42 98 124],[55 12 -2 62],4);
Convert the object to a structure and display the x,y coordinates for the third point.
pstruct = struct(polygon)
pstruct =
npoints: 4
xpoints: [4×1 int32]
ypoints: [4×1 int32]
If your Java methods return different types of data, then use the cell function to convert the data to
MATLAB types. Elements of the resulting cell array are converted according to the “Primitive Return
Types” on page 3-51 and “java.lang.Object Return Types” on page 3-51 tables.
Suppose that you call Java methods that return arguments of type java.lang.Double,
java.awt.Point, and java.lang.String. To run this example, create variables of these types.
import java.lang.* java.awt.*
3-53
3 Using Java Libraries from MATLAB
dblArray = javaArray('java.lang.Double',1,10);
for m = 1:10
dblArray(1,m) = Double(m * 7);
end
Convert each array to a cell array. You can use cellArray in MATLAB functions.
cellArray = {cell(dblArray),cell(ptArray),cell(strArray)}
cellArray =
[7] [14] [21] [28] [35] [42] [49] [56] [63] [70]
ans =
[1×1 java.awt.Point]
[1×1 java.awt.Point]
[1×1 java.awt.Point]
ans =
'one' 'two'
'three' 'four'
3-54
Handle Data Returned from Java Methods
See Also
More About
• “Pass Data to Java Methods” on page 3-46
• “How MATLAB Represents Java Arrays” on page 3-17
• “Converting Object Array Elements to MATLAB Types” on page 3-23
3-55
3 Using Java Libraries from MATLAB
1 On the Home tab, in the Environment section, click Preferences. Select MATLAB >
General > Java Heap Memory.
2 Select a Java heap size value using the slider or spin box.
Note Increasing the Java heap size decreases the amount of memory available for storing data in
arrays.
3 Click OK.
4 Restart MATLAB.
If the amount of memory you specified is not available upon restart, then MATLAB resets the value to
the default, and displays an error dialog box. To readjust the value, repeat the previous steps.
If increasing the heap size does not eliminate memory errors, then check your Java code for memory
leaks. Eliminate references to objects that are no longer useful. For more information, see
Troubleshooting Java SE.
3-56
Java Methods With Optional Input Arguments
To pass a scalar value 4 of type java.lang.Integer, create a variable numbers using javaArray.
oneNumber = java.lang.Integer(4);
numbers(1) = oneNumber;
Call myMethod.
myObj = MyClass;
myObj.myMethod(numbers)
See Also
javaArray
3-57
3 Using Java Libraries from MATLAB
For example, the code in this Java class ExampleClass creates a method fevalExample to call the
MATLAB sqrt function. This method is part of a larger application which might read data from a
device and then apply the MATLAB function on the data. In the fevalExample method, connect to
MATLAB using getCurrentMatlab. The application manages the data between the device and the
MATLAB calculation. MATLAB users call the fevalExample function to bring the data into MATLAB
for further action.
import com.mathworks.engine.*;
To call fevalExample from MATLAB, add ExampleClass to the Java class path. This example
assumes that the file is in your current folder. Create MATLAB object javaTest and call its
fevalExample function. The result is the value returned by sqrt.
javaaddpath(pwd)
javaTest = ExampleClass;
result = javaTest.fevalExample()
result = 2.0
Note Programs using the getCurrentMatlab method are supported on the MATLAB thread only. If
you call this functionality from an engine application, MATLAB displays an error.
See Also
com.mathworks.engine.MatlabEngine | “getCurrentMatlab”
Related Examples
• “MATLAB Engine API for Java” on page 12-2
3-58
Java Packages to Be Removed
See Also
3-59
4
MATLAB supports applications written in C, C++, or Fortran to read MAT-files. To create the
application, write your program using MATLAB APIs, then build using the mex command.
See Also
importdata
More About
• “Supported File Formats for Import and Export”
• “Save and Load Workspace Variables”
4-2
Custom Applications to Access MAT-Files
In this section...
“Why Write Custom Applications?” on page 4-3
“MAT-File Interface Library” on page 4-3
“Exchanging Data Files Between Platforms” on page 4-4
Before writing a custom application, determine if MATLAB meets your data exchange needs by
reviewing the following topics.
If these features are not sufficient, you can create custom C/C++ or Fortran programs to read and
write data files in the format required by your application. There are two types of custom programs:
• Standalone program — Run from a system prompt or execute in MATLAB (see “Run External
Commands, Scripts, and Programs” on page 21-3). Requires MATLAB libraries to build the
application.
• MEX file — Built and executed from the MATLAB command prompt. For information about
creating and building MEX files, see “C MEX File Applications”.
4-3
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
MAT-File Routines
The MAT-File Interface Library does not support MATLAB objects created by user-defined classes.
Do not create different MATLAB sessions on different threads using MAT-File API functions. MATLAB
libraries are not multithread safe so you can use these functions only on a single thread at a time.
Both types of files can be transported directly between machines: MATLAB source files because they
are platform independent, and MAT-files because they contain a machine signature in the file header.
MATLAB checks the signature when it loads a file and, if a signature indicates that a file is foreign,
performs the necessary conversion.
Using MATLAB across different machine architectures requires a facility for exchanging both binary
and ASCII data between the machines. Examples of this type of facility include FTP, NFS, and Kermit.
When using these programs, be careful to transmit MAT-files in binary file mode and MATLAB source
files in ASCII file mode. Failure to set these modes correctly corrupts the data.
4-4
MAT-File API Library and Include Files
The bin folder contains the run-time version of the shared libraries:
The bin/arch folder, where arch is the value returned by the computer('arch') command,
contains the shared libraries.
4-5
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
The bin/arch folder, where arch is the value returned by the computer('arch') command,
contains the shared libraries. For example, on Apple macOS 64-bit systems, the folder is bin/
maci64:
Example Files
The extern/examples/eng_mat folder contains C/C++ and Fortran source code for examples
demonstrating how to use the MAT-file routines.
4-6
What You Need to Build Custom Applications
To exchange custom data with MATLAB data, use a MAT-file, a MATLAB format binary file. You do not
need the MAT-file format specifications because the MAT-File Interface Library provides the API to
the data. You need to know the details of your data to map it into MATLAB data. Get this information
from your product documentation, then use the mxArray type in the Matrix Library to declare the
data in your program.
In your custom program, use functions in the MATLAB C Matrix or Fortran Matrix API:
To build the application, use the mex build script with the -client engine option.
See Also
mxArray | mex
More About
• “MAT-File API Library and Include Files” on page 4-5
• “Build Engine Applications with IDE” on page 11-24
External Websites
• Supported and Compatible Compilers
4-7
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
The following topics describe these steps in detail. To see the code, open the file in the MATLAB
Editor. The C statements in these topics are code snippets shown to illustrate a task. The statements
in the topics are not necessarily sequential in the source file.
4-8
Copy External Data into MAT-File Format with Standalone Programs
The following statements declare the type and size for variables extString and extData.
#define BUFSIZE 256
char extString[BUFSIZE];
double extData[9];
Use these variables to read values from a file or a subroutine available from your product. This
example uses initialization to create the external data.
const char *extString = "Data from External Device";
double extData[9] = { 1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0 };
To create a variable of the proper size and type, select one of the mxCreate* functions from the MX
Matrix Library.
The size of extData is 9, which the example copies into a 3-by-3 matrix. Use the
mxCreateDoubleMatrix function to create a two-dimensional, double-precision, floating-point
mxArray initialized to 0.
pVarNum = mxCreateDoubleMatrix(3,3,mxREAL);
The C memcpy function copies blocks of memory. This function requires pointers to the variables
extData and pVarNum. The pointer to extData is (void *)extData. To get a pointer to pVarNum,
4-9
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
use one of the mxGet* functions from the Matrix API. Since the data contains only real values of type
double, this example uses the mxGetPr function.
The following statement initializes the pVarChar variable with the contents of extString.
pVarChar = mxCreateString(extString);
MATFile *pmat;
const char *myFile = "matimport.mat";
pmat = matOpen(myFile, "w");
Clean Up
To close the file:
matClose(pmat);
To free memory:
mxDestroyArray(pVarNum);
mxDestroyArray(pVarChar);
copyfile(fullfile(matlabroot,'extern','examples','eng_mat',matimport.c'),'.','f')
mex -v -client engine matimport.c
!matimport
4-10
Copy External Data into MAT-File Format with Standalone Programs
load matimport.mat
whos
See Also
Related Examples
• “Table of MAT-File Source Code Files” on page 4-18
4-11
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
Create MAT-File in C
The matcreat.c example illustrates how to use the library routines to create a MAT-file that you can
load into the MATLAB workspace. The program also demonstrates how to check the return values of
MAT-file function calls for read or write failures. To see the code, open the file in MATLAB Editor.
After building the program, run the application. This program creates mattest.mat, a MAT-file that
you can load into MATLAB. To run the application, depending on your platform, either double-click its
icon or enter matcreat at the system prompt:
matcreat
See Also
Related Examples
• “Table of MAT-File Source Code Files” on page 4-18
4-12
Read MAT-File in C/C++
After building the program, run the application. This program reads the mattest.mat MAT-file
created by the “Create MAT-File in C or C++” on page 4-12 example. To run the application,
depending on your platform, either double-click its icon or enter matdgns at the system prompt.
matdgns mattest.mat
Reading file mattest.mat...
Directory of mattest.mat:
GlobalDouble
LocalString
LocalDouble
See Also
Related Examples
• “Create MAT-File in Fortran” on page 4-14
• “Table of MAT-File Source Code Files” on page 4-18
4-13
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
After building the program, run the application. This program creates a MAT-file, matdemo.mat, that
you can load into MATLAB. To run the application, depending on your platform, either double-click its
icon or type matdemo1 at the system prompt:
matdemo1
Note For an example of a Microsoft Windows standalone program (not MAT-file specific), see
engwindemo.c in the matlabroot\extern\examples\eng_mat folder.
See Also
Related Examples
• “Read MAT-File in C/C++” on page 4-13
• “Table of MAT-File Source Code Files” on page 4-18
4-14
Read MAT-File in Fortran
matdemo2
Directory of Mat-file:
String
Numeric
Getting full array contents:
1
Retrieved String
With size 1-by- 33
3
Retrieved Numeric
With size 3-by- 3
See Also
Related Examples
• “Table of MAT-File Source Code Files” on page 4-18
4-15
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
The MAT-File Interface Library lets you access MATLAB arrays (type mxArray) in a MAT-file. To work
directly with an mxArray in a C/C++ application, use functions in the Matrix Library.
You can find examples for working with the mxArray type in the matlabroot/extern/
examples/mex and matlabroot/extern/examples/mx folders. The following topics show C code
examples, based on these MEX examples, for working with cells and structures. The examples show
how to read cell and structure arrays and display information based on the type of the mxArray
within each array element.
If you create an application from one of the MEX examples, here are some tips for adapting the code
to a standalone application.
• The MAT-file example, matdgns.c, shows how to open and read a MAT-file. For more information
about the example, see “Read MAT-File in C/C++” on page 4-13.
• The MEX example, explore.c, has functions to read any MATLAB type using the mxClassID
function. For more information about the example, see “Using Data Types” on page 7-9.
• Some MEX examples use functions, such as mexPrintf, from the C MEX API library, libmex. You
do not need to use these functions to work with an mxArray, but if your program calls any of
them, you must link to the MEX Library. To do this, add libmex.lib to the link statement.
After building the program, run the application on the MAT-file, testpatient.mat.
save testpatient.mat
4-16
Work with mxArrays
After building the program, run the application on the MAT-file, testcells.mat.
0: string
1: numeric class
2: numeric class
See Also
Related Examples
• “Table of MAT-File Source Code Files” on page 4-18
4-17
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
To build a code example, first copy the file to a writable folder, such as c:\work on your Windows
path.
copyfile(fullfile(matlabroot,'extern','examples','eng_mat',...
'filename'), fullfile('c:','work'))
Example Description
matcreat.c C program that demonstrates how to use the library routines to create
a MAT-file that you can load into MATLAB.
matcreat.cpp C++ version of the matcreat.c program.
matdgns.c C program that demonstrates how to use the library routines to read
and diagnose a MAT-file.
matdemo1.F Fortran program that demonstrates how to call the MATLAB MAT-file
functions from a Fortran program.
matdemo2.F Fortran program that demonstrates how to use the library routines to
read the MAT-file created by matdemo1.F and describe its contents.
matimport.c C program based on matcreat.c used in the example for writing
standalone applications.
matreadstructarray.c C program based on explore.c to read contents of a structure array.
matreadcellarray.c C program based on explore.c to read contents of a cell array.
4-18
Build on macOS and Linux Operating Systems
In this section...
“Set Run-Time Library Path” on page 4-19
“Build Application” on page 4-20
Replace the terms envvar and pathspec with the appropriate values from the table. For example,
on a macOS system use:
setenv DYLD_LIBRARY_PATH
matlabroot/bin/maci64:matlabroot/sys/os/maci64
envvar = pathspec:envvar
export envvar
Replace the terms envvar and pathspec with the appropriate values from the table. For example,
on a macOS system use:
DYLD_LIBRARY_PATH=matlabroot/bin/maci64:matlabroot/sys/os/maci64:$DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH
4-19
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
Build Application
To compile and link MAT-file programs, use the mex script with the -client engine option.
This example shows how to build the example matcreat.c. Use this example to verify the build
configuration for your system. matcreat is C program that demonstrates how to use the MAT-File
API routines to create a MAT-file that you can load into MATLAB.
To build the example, first copy the source code to a writable folder on your path.
copyfile(fullfile(matlabroot,'extern','examples','eng_mat','matcreat.c'),'.','f')
To modify the build instructions for your particular compiler, use the -v -n options to view the
current compiler and linker settings. Then, modify the settings using the mex varname=varvalue
option.
See Also
mex
Related Examples
• “Create MAT-File in C or C++” on page 4-12
4-20
Build on Windows Operating Systems
This example shows how to build the example matcreat.c. Use this example to verify the build
configuration for your system. matcreat is C program that demonstrates how to use the MAT-File
API routines to create a MAT-file that you can load into MATLAB. For more information, see “Create
MAT-File in C or C++” on page 4-12.
To build the example, first copy the source code to a writable folder on your path.
copyfile(fullfile(matlabroot,'extern','examples','eng_mat','matcreat.c'),'.','f')
To modify the build instructions for your particular compiler, use the -v -n options to view the
current compiler and linker settings. Then, modify the settings using the mex varname=varvalue
option.
See Also
mex
Related Examples
• “Create MAT-File in C or C++” on page 4-12
• “Build Windows Engine Application” on page 11-10
4-21
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran
If you specify other run-time libraries in your build command, then these libraries must be present on
the end-user’s computer. These library files must reside in the same folder as the libmx library. You
can identify these libraries using the platform-specific commands shown in the following table.
To find library dependencies on Windows systems, use the third-party product Dependency Walker.
This free utility scans Windows modules and builds a hierarchical tree diagram of all dependent
modules. For each module found, it lists all the functions exported by that module, and which of those
functions are called by other modules. See How do I determine which libraries my MEX-file or stand-
alone application requires? for information on using the Dependency Walker.
Drag and drop the libmat.dll file into the Depends window. Identify the dependent libraries and
add them to your IDE configuration.
4-22
5
5-2
What Types of Files Define Your Library?
• One or more header or source files that contain declarations of all the functions exported by the
library. You should be able to compile these files in a C++ development environment and use the
functionality in C++ applications.
• A shared library file — .dll on Windows, .so on Linux, or .dylib on macOS. If the library is
completely defined in the header or source files, then the library file is optional.
The library file must be built in release mode by using with a C++ compiler that MATLAB
supports. If you build the library in debug mode, it might be incompatible with MATLAB, resulting
in a termination of the program.
For information about building an interface, see “Steps to Publish a MATLAB Interface to a C++
Library” on page 5-8. The first step is to generate a MATLAB library definition file depending on
what types of files define your library. Your library might contain combinations of header files, CPP
source files, and shared library files.
See Also
clibgen.generateLibraryDefinition
5-3
5 Calling Functions in C++ Shared Libraries from MATLAB
You can use library example code as a starting point to create an .hpp header file. Example code
contains the relevant header files in #include statements. Copy the .cpp code into a text editor.
Remove the main function and its implementation. Save the file with the .cpp file extension. The
name of this file is the SourceFiles argument for the clibgen.buildInterface or
clibgen.generateLibraryDefinition functions.
Compiler Dependencies
To build a MATLAB interface for a C++ library, you need an installed, C++ compiler that MATLAB
supports. For an up-to-date list of supported compilers, see Supported and Compatible Compilers.
You must build the interface to the library by using the same compiler that was used to build the C++
library. If your library is header-only (does not use a shared library file), then you can choose any
supported C++ compiler to build the interface library.
See Also
More About
• “Steps to Publish a MATLAB Interface to a C++ Library” on page 5-8
• “Choose a C++ Compiler” on page 8-19
5-4
Requirements for Building Interface to C++ Libraries
External Websites
• Supported and Compatible Compilers
5-5
5 Calling Functions in C++ Shared Libraries from MATLAB
You can set the path each time that you work on the library or set it permanently by setting values in
the system environment. To add the library to the system path permanently, refer to your operating
system documentation.
dllPath = 'rtPath';
syspath = getenv('PATH');
setenv('PATH',[dllPath ';' syspath]);
Note If you use these commands, then you must set the path each time that you start MATLAB.
set PATH=rtPath;%PATH%
• Linux C shell:
LD_LIBRARY_PATH=rtPath:LD_LIBRARY_PATH
export LD_LIBRARY_PATH
• macOS C shell:
setenv DYLD_LIBRARY_PATH matlabroot/bin/maci64:matlabroot/sys/os/maci64
DYLD_LIBRARY_PATH=matlabroot/bin/maci64:matlabroot/sys/os/maci64:DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH
Note Start MATLAB in the same operating system prompt where you set the PATH variable. To verify
the updated system path, in MATLAB type:
getenv('PATH')
5-6
Set Run-Time Library Path for C++ Interface
Note If you use these commands, then you must set the path each time that you open the operating
system prompt.
See Also
More About
• “Call Functions in C++ Shared Library” on page 5-39
• Append library path to "DYLD_LIBRARY_PATH" in MAC
5-7
5 Calling Functions in C++ Shared Libraries from MATLAB
• For requirements, see “Requirements for Building Interface to C++ Libraries” on page 5-4.
• For Step 1: Generate, see clibgen.generateLibraryDefinition.
• For Step 2: Define, see “Define MATLAB Interface for C++ Library” on page 5-24.
5-8
Steps to Publish a MATLAB Interface to a C++ Library
• For Step 3: Build, see “Build C++ Library Interface and Review Contents” on page 5-37.
• For Step 4: Test, see “Call Functions in Windows Interface to C++ Shared Library” on page 5-13
or “Call Functions in Linux Interface to C++ Shared Library” on page 5-15.
• For Step 5: Distribute, see “Create and Share Toolboxes”.
See Also
clibgen.generateLibraryDefinition | build
More About
• “Requirements for Building Interface to C++ Libraries” on page 5-4
• “Define MATLAB Interface for C++ Library” on page 5-24
• “Publish Help Text for MATLAB Interface to C++ Library” on page 5-20
• “Build C++ Library Interface and Review Contents” on page 5-37
• “Call Functions in C++ Shared Library” on page 5-39
• “Create and Share Toolboxes”
• “Limitations to C/C++ Support” on page 5-40
5-9
5 Calling Functions in C++ Shared Libraries from MATLAB
See Also
Related Examples
• “Header File and Shared Object File on Linux” on page 5-95
• “Header File and Dynamic Shared Library File on macOS” on page 5-12
5-10
Header and CPP Source Files
fullfile(matlabroot,"extern","examples","cpp_interface");
See Also
Related Examples
• “Header-Only HPP File” on page 5-17
5-11
5 Calling Functions in C++ Shared Libraries from MATLAB
fullfile(matlabroot,"extern","examples","cpp_interface");
See Also
Related Examples
• “Header File and Import Library File on Windows” on page 5-10
• “Header File and Shared Object File on Linux” on page 5-95
5-12
Call Functions in Windows Interface to C++ Shared Library
C:\Documents\matrixexample\matrixlib
Set Paths
At the operating system prompt, add the path to the C++ shared library file. For more information,
see “Set Run-Time Library Path for C++ Interface” on page 5-6.
set PATH=rtPath;%PATH%
For example, type this command where release is the MATLAB release folder like R2021a.
set PATH=C:\Program Files\MATLAB\release\extern\examples\cpp_interface\win64\mingw64;%PATH%
Start MATLAB in the same system prompt where you set the PATH variable.
syspath = split(getenv('PATH'),';')
To add the MATLAB interface file to the MATLAB path, navigate to the folder you used in the
“Generate Interface on Windows” on page 5-94 step.
addpath(pwd)
View Help
At the MATLAB command prompt, display help for the interface. In the example, the
clibgen.generateLibraryDefinition command changed the name of the interface to
matrixOperations to matrixlib. Type this command to load the package.
doc clib.matrixlib.Mat
doc clib.matrixlib
Classes contained in clib.matrixlib:
Mat - clib.matrixlib.Mat Representation of C++ class Mat
To display signatures for the package function, click the links for addMat, updateMatByX, and
updateMatBySize.
clib.matrixlib.addMat Representation of C++ function addMat
inputs
mat read-only clib.matrixlib.Mat
5-13
5 Calling Functions in C++ Shared Libraries from MATLAB
outputs
RetVal int32
To display information about class clib.matrixlib.Mat, click the link for Mat.
clib.matrixlib.Mat Representation of C++ class Mat
Method Summary:
Mat - clib.matrixlib.Mat Constructor of C++ class Mat
Mat - clib.matrixlib.Mat Constructor of C++ class Mat
setMat - clib.matrixlib.Mat.setMat Method of C++ class Mat
getMat - clib.matrixlib.Mat.getMat Method of C++ class Mat
getLength - clib.matrixlib.Mat.getLength Method of C++ class Mat
copyMat - clib.matrixlib.Mat.copyMat Method of C++ class Mat
To display constructor and method signatures, use the methods or methodsview functions. For
example, type:
methodsview clib.matrixlib.Mat
retMat =
1 2 3 4 5
See Also
More About
• “Header File and Import Library File on Windows” on page 5-10
• “Set Run-Time Library Path for C++ Interface” on page 5-6
• “Display Help for MATLAB Interface to C++ Library” on page 5-18
• “Header File and Shared Object File on Linux” on page 5-95
• “Call Functions in Linux Interface to C++ Shared Library” on page 5-15
5-14
Call Functions in Linux Interface to C++ Shared Library
Set Paths
At the operating system prompt, add the path to the C++ shared library file. For more information,
see “Set Run-Time Library Path for C++ Interface” on page 5-6. Use rtPath as the output of:
rtPath = fullfile(matlabroot,"extern","examples","cpp_interface","glnxa64")
• C shell command:
LD_LIBRARY_PATH=rtPath:LD_LIBRARY_PATH
export LD_LIBRARY_PATH
Start MATLAB in the same system prompt where you set the PATH variable.
syspath = split(getenv('PATH'),';')
addpath("~/MATLAB/publisher/matrixexample/matrixlib")
View Help
At the MATLAB command prompt, display help for the interface. In the example, the
clibgen.generateLibraryDefinition command changed the name of the interface to
matrixOperations to matrixlib. Type this command to load the package.
doc clib.matrixlib.Mat
doc clib.matrixlib
Classes contained in clib.matrixlib:
Mat - clib.matrixlib.Mat Representation of C++ class Mat
To display signatures for the package function, click the links for addMat, updateMatByX, and
updateMatBySize.
clib.matrixlib.addMat Representation of C++ function addMat
inputs
mat read-only clib.matrixlib.Mat
outputs
RetVal int32
5-15
5 Calling Functions in C++ Shared Libraries from MATLAB
mat clib.matrixlib.Mat
X int32
outputs
To display information about class clib.matrixlib.Mat, click the link for Mat.
clib.matrixlib.Mat Representation of C++ class Mat
Method Summary:
Mat - clib.matrixlib.Mat Constructor of C++ class Mat
Mat - clib.matrixlib.Mat Constructor of C++ class Mat
setMat - clib.matrixlib.Mat.setMat Method of C++ class Mat
getMat - clib.matrixlib.Mat.getMat Method of C++ class Mat
getLength - clib.matrixlib.Mat.getLength Method of C++ class Mat
copyMat - clib.matrixlib.Mat.copyMat Method of C++ class Mat
To display constructor and method signatures, use the methods or methodsview functions. For
example, type:
methodsview clib.matrixlib.Mat
retMat =
1 2 3 4 5
See Also
More About
• “Header File and Shared Object File on Linux” on page 5-95
• “Set Run-Time Library Path for C++ Interface” on page 5-6
• “Display Help for MATLAB Interface to C++ Library” on page 5-18
5-16
Header-Only HPP File
This library defines classes representing students and teachers. After you publish this library,
MATLAB users can call functions in the clib.school package to create Student and Teacher
objects and specify names and ages.
MATLAB provides the header file for you to use in this example in this folder:
fullfile(matlabroot,"extern","examples","cpp_interface");
See Also
Related Examples
• “Header and CPP Source Files” on page 5-11
5-17
5 Calling Functions in C++ Shared Libraries from MATLAB
• doc and help — View classes and functions in a package. When you publish an interface, you can
add descriptive text. For more information, see “Publish Help Text for MATLAB Interface to C++
Library” on page 5-20.
• methods — View constructor, method, and package function names for a class.
• methods with '-full' option — View constructor, method, and package function signatures.
• methodsview — Table representation of method signatures. You might find the methodsview
window easier to use as a reference guide because you do not need to scroll through the
Command Window to find information.
If you created the school interface in the example “Header-Only HPP File” on page 5-17, then you
can use it in this example. With the schoolInterface.dll file in the current folder, type:
addpath('.')
doc clib.school.
then press Tab. This command loads the package. MATLAB displays a list of members. To view the
package, press the Backspace key to remove the period, then press Enter. MATLAB displays:
Classes contained in clib.school:
Person - clib.school.Person Representation of C++ class Person
Teacher - clib.school.Teacher Representation of C++ class Teacher
Student - clib.school.Student Representation of C++ class Student
To display the inputs and outputs for the getName package function, click the getName link.
To display class methods, call the methods function for each class. For example, type:
methods clib.school.Person
To display function signatures, call the methodsview function for each class. For example, type:
methodsview clib.school.Person
The function opens a window that displays the methods and information about arguments and
returned values. For example, the signatures for the constructors are:
5-18
Display Help for MATLAB Interface to C++ Library
See Also
doc | methods | methodsview
More About
• “Publish Help Text for MATLAB Interface to C++ Library” on page 5-20
5-19
5 Calling Functions in C++ Shared Libraries from MATLAB
Note If you already loaded the clib package, for example, by calling doc or calling a class
constructor, then you must restart MATLAB to change the interface.
MATLAB reads Doxygen style, C++ comments, but is not a Doxygen parser. For example, MATLAB
processes Doxygen @brief and @details commands to add content to a class or function
description. MATLAB reads @param and @return commands to augment argument descriptions.
MATLAB uses the content of @code commands to provide code examples. Within any Doxygen
command, MATLAB ignores formatting tags. For example, a Doxygen parser displays word as shown
in this tag <b>word</b> in bold font. MATLAB simply includes the text <b>word</b> in the help.
MATLAB does not display html tags <code>, </code>, <p>, </p>, and <br>.
By default, MATLAB copies C++ comments from library header and source files into the
Description and, if available, DetailedDescription arguments for these methods.
Enumerations optionally have EnumerantDescriptions arguments. You can review and edit the
content by using the MLX library definition file.
• addClass
• addConstructor
• addEnumeration
• addFunction
• addFunctionType
• addMethod
• addOpaqueType
• addProperty
5-20
Publish Help Text for MATLAB Interface to C++ Library
If you do not want to copy C++ comments from the header and source files, then call
clibgen.generateLibraryDefinition with the “GenerateDocumentationFromHeaderFiles”
argument set to false. You can still enter text in the Description argument in the definition file.
If you created the interface, move to the folder with the defineschool.mlx file and school folder
with the interface library. Alternatively, create the interface:
copyfile(fullfile(matlabroot,'extern','examples','cpp_interface','school.hpp'),'.','f')
clibgen.generateLibraryDefinition('school.hpp')
build(defineschool)
addpath("school")
summary(defineschool)
The default help text for class Person is Representation of C++ class Person. To display the
help, type:
doc clib.school
To modify this text, edit defineschool.mlx. Search for the text Representation of C++ class
Person.
to:
To rebuild the library, restart MATLAB. Navigate to the folder containing defineschool.mlx. Delete
the existing interface file.
delete school\*.dll
build(defineschool)
addpath school
doc clib.school
5-21
5 Calling Functions in C++ Shared Libraries from MATLAB
After building the interface in the example, display the MATLAB help for the Initialize method.
help clib.MyXercesLibrary.xercesc_3_1.XMLPlatformUtils.Initialize
clib.MyXercesLibrary.xercesc_3_1.XMLPlatformUtils.Initialize Method of C++ class xercesc_3_1::XMLPlatformUtils.
Perform per-process parser initialization
Inputs
locale read-only string
locale The locale to use for messages.
panicHandler clib.MyXercesLibrary.xercesc_3_1.PanicHandler
panicHandler Application's panic handler, application owns this handler.
Application shall make sure that the plugged panic handler persists
through the call to XMLPlatformUtils::Terminate().
memoryManager clib.MyXercesLibrary.xercesc_3_1.MemoryManager
memoryManager Plugged-in memory manager which is owned by the
application. Applications must make sure that the
plugged-in memory manager persist through the call to
5-22
Publish Help Text for MATLAB Interface to C++ Library
XMLPlatformUtils::Terminate()
No outputs
See Also
clibgen.generateLibraryDefinition | build
More About
• “Define MATLAB Interface for C++ Library” on page 5-24
• “Header-Only HPP File” on page 5-17
• “Modify Library Help” on page 5-69
5-23
5 Calling Functions in C++ Shared Libraries from MATLAB
An example of information that the publisher must define relates to the use of pointers to pass data to
functions. A pointer is a location in memory that indicates the start of a block of data. To pass this
data to MATLAB safely, the publisher must specify the size of the data. The function documentation
indicates the size of the data, perhaps as an additional input argument. Using the MATLAB definition
file, the publisher specifies the value, and then MATLAB creates the equivalent MATLAB function
signature. To display function signatures, see “Display Help for MATLAB Interface to C++ Library”
on page 5-18.
• To specify if a pointer argument is read-only input, output only, or a modifiable input argument,
use the DIRECTION on page 5-36 parameter.
• If a pointer argument is used for array data, then dimension information is required to convert the
array between C++ and MATLAB. Use the SHAPE on page 5-28 parameter to specify this
information.
• C++ has many types representing string arguments. You might need to specify MLTYPE on page
5-35 and SHAPE on page 5-28 values so that MATLAB can correctly convert the C++ type to
the MATLAB string type.
MATLAB offers code suggestions for values of these parameters. To activate suggestions for a specific
parameter:
5-24
Define MATLAB Interface for C++ Library
Autodefine Arguments
You can direct MATLAB to autodefine the type and shape of specific argument types by using
clibgen.generateLibraryDefinition and clibgen.buildInterface name-value arguments.
The options are:
• To treat all const character pointers in the library as null-terminated C strings, set the
“TreatConstCharPointerAsCString” argument to true.
• To treat all object pointers in the library as scalars, set the “TreatObjectPointerAsScalar”
argument to true.
When you validate the library definition, you might get errors about duplicate MATLAB signatures. To
resolve these errors, see “Reconcile MATLAB Signature Conflicts” on page 5-25.
definelibname
If there is a conflict, MATLAB displays an error with a link to the code in the definition file. To resolve
the conflict, choose one of the following:
After modifying the definition file, rerun the file to validate your edits.
Customize Content
Review the renaming scheme used by MATLAB to replace invalid names. For more information, see
“C++ Names That Are Invalid in MATLAB” on page 5-43.
Review autogenerated help. MATLAB copies some C++ comments into Description and
DetailedDescription arguments. You can modify or replace this content, which is the basis of the
doc command for end users.
5-25
5 Calling Functions in C++ Shared Libraries from MATLAB
If you build an interface A to this library, MATLAB creates overloaded functions that have signatures
for these instantiations.
summary(defineA)
Class clib.libname.A
Constructors:
clib.libname.A(clib.libname.A)
clib.libname.A()
No Methods defined
No Properties defined
Functions
clib.libname.show(int32)
clib.libname.show(double)
clib.libname.show(clib.libname.A)
The C++ interface also generates unique function names based on the signature types. To view the
unique names, use the TemplateUniqueName property.
d = defineA;
d.Functions(1:3).TemplateUniqueName
ans = "clib.libname.show_int_"
ans = "clib.libname.show_double_"
ans = "clib.libname.show_AConst__"
You can customize these names in the library definition file. For example, change the name of the
function for the class object clib.libname.show_AConst__. Restart MATLAB and edit
defineA.mlx. Locate the addFunction statement for the show_AConst__ function and change the
"TemplateUniqueName" name-value argument. Replace show_AConst__ with a new name, for
example showObjectA. Update the "Description" name-value argument by replacing
clib.libname.show with the new name clib.libname.showObjectA and modifying the help
text to read Representation of C++ function show for class A.
"Description", "clib.libname.showObjectA Representation of C++ function show for class A.");
help clib.libname.showObjectA
clib.libname.showObjectA Representation of C++ function show for class A.
Inputs
a read-only clib.libname.A
No outputs
For more information, see “Use Function and Member Function Templates” on page 5-91.
Dimension Matching
If the number of dimensions of a MATLAB argument is larger than the corresponding C++ parameter,
then MATLAB deletes singleton dimensions from the left until the number of dimensions matches
5-26
Define MATLAB Interface for C++ Library
each other. If all singleton dimensions are deleted and the MATLAB argument is larger than the C++
parameter, then MATLAB produces an exception.
If the number of dimensions of the MATLAB argument is smaller than the C++ parameter, MATLAB
adds singleton dimensions. By default, MATLAB inserts singleton dimensions at the beginning of the
argument. To insert singleton dimensions at the end of the argument, set
'AddTrailingSingletons' to true in the defineArgument functions - defineArgument
(ConstructorDefinition), defineArgument (FunctionDefinition), and defineArgument
(MethodDefinition).
For example, a C++ library contains two functions that have input arguments in interface libname
defined as follows:
void setImages(const uint8_t * images, int numOfImages, int height, int width);
void setColorImage(const uint8_t * image, int height, int width, int colorDepth);
size(myImage)
ans =
768 1024
When you call setImages, MATLAB adjusts the size of myImage to [1, 768, 1024].
setImages(myImage)
When you call setColorImage MATLAB adjusts the size of myImage to [768, 1024, 1].
setColorImage(myImage)
See Also
clibgen.generateLibraryDefinition | clibgen.buildInterface
More About
• “Publish Help Text for MATLAB Interface to C++ Library” on page 5-20
• “Define Missing SHAPE Parameter” on page 5-28
• “Define Missing MLTYPE Parameter” on page 5-35
• “Define Missing DIRECTION Parameter” on page 5-36
• “Use Function and Member Function Templates” on page 5-91
• “C++ Names That Are Invalid in MATLAB” on page 5-43
• “Lifetime Management of C++ Objects in MATLAB” on page 5-67
• “Limitations to C/C++ Support” on page 5-40
• “Unsupported Data Types” on page 5-59
5-27
5 Calling Functions in C++ Shared Libraries from MATLAB
Note These pointer types can only be used as scalars. Define SHAPE as 1 in the MLX file.
The following examples of constructs defined in the sample cppUseCases.hpp header file show you
how to specify the shape of an argument. In these tables, the descriptions for the functions in the C+
+ Signature and Role of Pointer column are based on assumed knowledge of the arguments. The
signature itself does not provide this information.
To view the cppUseCases.hpp header file and its generated definition file, see “Sample C++ Library
Definition File” on page 5-38.
5-28
Define Missing SHAPE Parameter
5-29
5 Calling Functions in C++ Shared Libraries from MATLAB
5-30
Define Missing SHAPE Parameter
5-31
5 Calling Functions in C++ Shared Libraries from MATLAB
This function updates the input argument chArray. For argument chArray, set DIRECTION to
The length of chArray is len. "inputoutput" and SHAPE to "len".
5-32
Define Missing SHAPE Parameter
defineArgument(readConstFixedCStrArrayDefinition, ..
"strs", "string", "input", [5, "nullTerminated"]
You can use a public, nonstatic C++ method as the SHAPE parameter for a nonstatic property or for
the return type of a nonstatic method in the same class. The method must be fully implemented,
without input arguments, and the return type must be defined as a C++ type int.
You can use a combination of parameters, properties and methods as the SHAPE parameter for a
method return type. If the specified SHAPE exists as both a parameter and a method or property, then
parameters take precedence. In this case SHAPE is treated as a parameter.
5-33
5 Calling Functions in C++ Shared Libraries from MATLAB
channels.
class A
{
public:
int rows;
int cols;
int* rowData;
int channels();
};
The size of the array For the return value of method getData, set SHAPE to an array of
returned by getData is rows, cols, and channels.
defined by data members
rows and cols and by the defineOutput(getDataDefinition, "RetVal", "clib.array.libname.Int", ["r
result of the channels
method.
class B
{
public:
int rows;
int cols;
int* rowData;
int channels();
const int* getData();
};
The size of the array For the return value of method getData, set SHAPE to an array of
returned by getData is parameter rows and method channels.
defined by the rows
parameter and the result of defineOutput(getDataDefinition, "RetVal", "clib.array.C.Int", ["rows","
method channels.
class C
{
public:
int rows;
int channels();
const int* getData (int rows);
};
5-34
Define Missing MLTYPE Parameter
If the C++ type for the argument is a string, then use these options to choose values for the MLTYPE
and SHAPE arguments.
• wchar_t
• char16_t
• char32_t
See Also
Related Examples
• “C++ to MATLAB Data Type Mapping” on page 5-49
5-35
5 Calling Functions in C++ Shared Libraries from MATLAB
If a pointer argument is used to pass data to the function, then it must appear as an input
argument in the MATLAB signature.
If a pointer argument is used to retrieve data from the function, then it must appear as an output
argument in the MATLAB signature.
• "inputoutput"—Input and output argument
If a pointer argument is used to both pass and return data, then it must appear as both an input
argument and an output argument.
Note Default arguments with direction specified as OUT are not supported. Define these with
DIRECTION as "input" or "inputoutput" in the MLX file.
For example, suppose that a C++ function passData has the following signature. The argument
data might be an input to the function, the return value of the function, or input that the function
modifies and returns. The documentation of the function tells you how the function uses the argument
data.
Assuming data is a scalar double value, this table shows the MATLAB signature based on its role.
5-36
Build C++ Library Interface and Review Contents
Note If library functionality is missing, the library might contain unsupported language features or
data types on page 5-40. For details, run clibgen.generateLibraryDefinition with the
'Verbose' option set to true.
build(definelibName)
addpath libName
summary(definelibName)
One-Step Build
If your library does not contain pointers or other constructs that require definition, you do not need
to create a definition file. Call clibgen.buildInterface directly on the C++ header and library
files. For example, to build library libName defined by header file header.hpp, type:
clibgen.buildInterface('header.hpp','Verbose',true)
addpath libName
Use the doc function to open the Help browser which provides links to display help for library
functionality. For example, to verify the included classes for library libname, type:
doc clib.libname
Click a link for a class. MATLAB opens a new tab. To display help for class ClassName, click the
Constructor Summary link and verify the content. Click the Property Summary links. Scan the
Method Summary for clib.libname.ClassName methods.
See Also
build | clibgen.LibraryDefinition
More About
• “Build MATLAB Interface to C++ Library”
• “Publish Help Text for MATLAB Interface to C++ Library” on page 5-20
• “Define MATLAB Interface for C++ Library” on page 5-24
5-37
5 Calling Functions in C++ Shared Libraries from MATLAB
This example header file contains C++ language constructs that need further definition from a
publisher to create a MATLAB interface to the library. The class constructors and functions are C++
signatures only. There is no implementation and they are not used in any examples.
Use the corresponding definecppUseCases.mlx file to learn how to add the functionality to the
MATLAB interface.
edit(fullfile(matlabroot,"extern","examples","cpp_interface","cppUseCases.hpp"))
The definecppUseCases.mlx library definition file is created from the cppUseCases.hpp header
file using the clibgen.generateLibraryDefinition function. After generating the library
definition file, replace <SHAPE>, <DIRECTION>, and <MLTYPE> text with appropriate values so that
MATLAB can create equivalent function signatures. For details about providing the information for all
constructors and functions in this library, see “Define MATLAB Interface for C++ Library” on page 5-
24.
edit definecppUseCases.mlx
For example, assume that the input to function addClassByPtr is a pointer to class ns::MyClass2.
Search for this text:
Argument myc2 is not defined for MATLAB. See this statement, which contains <SHAPE>:
defineArgument(addClassByPtrDefinition, "myc2",
"clib.cppUseCases.ns.MyClass2", "input", <SHAPE>);
defineArgument(addClassByPtrDefinition, "myc2",
"clib.cppUseCases.ns.MyClass2", "input", 1);
Uncomment the seven lines defining the function and save the MLX file.
%validate
5-38
Call Functions in C++ Shared Library
Set Path
Put the MATLAB interface file on the MATLAB path by using the addpath function.
MATLAB looks for the library interface file on the MATLAB path. The interface file for library
libname is libnameInterface.ext, where ext is the platform-specific file extension for a shared
library file on page 5-4.
The C++ shared library file and its dependencies, if any, must be on your system path or run-time
search path (rpath). For more information, see “Set Run-Time Library Path for C++ Interface” on
page 5-6.
Display Help
The MATLAB help and doc functions provide help for members of the library. For example, to display
help for function funcname in library libname, type:
help clib.libname.funcname
Call Function
To call a function in a C++ library, use the MATLAB clib package. MATLAB automatically loads the
library when you type:
memberName = "fully-qualified-class-member";
clib.memberName
After MATLAB loads the library, you can use tab completion to view the members of the clib
package.
For example, to call function funcname in library libname, type the following statement. funcname
defines the input arguments arg1, arg2, ... and the output argument retVal.
See Also
More About
• “Set Run-Time Library Path for C++ Interface” on page 5-6
• “Display Help for MATLAB Interface to C++ Library” on page 5-18
• “C++ to MATLAB Data Type Mapping” on page 5-49
5-39
5 Calling Functions in C++ Shared Libraries from MATLAB
• std::string
• std::wstring
• std::u16string
• std::u32string
• std::vector
• std::shared_ptr
• std::function
If a library uses these data types, then the functionality is not included in the MATLAB interface to
the library, and MATLAB displays messages like:
Did not add member 'methodName' to class 'ClassName' at HeaderFile.h:290.
'long double' is not a supported type.
5-40
Limitations to C/C++ Support
When you build a library containing these features or usage, MATLAB displays:
Warning: Some C++ language constructs in the header file are not supported and not imported.
5-41
5 Calling Functions in C++ Shared Libraries from MATLAB
See Also
More About
• “C++ to MATLAB Data Type Mapping” on page 5-49
• “C++ Limitation Workaround Examples” on page 5-72
5-42
C++ Names That Are Invalid in MATLAB
MATLAB automatically renames classes, member functions, non-member functions, and enumerations
with C++ names that are invalid in MATLAB by using the matlab.lang.makeValidName function.
Enumerants and data members with C++ names that are invalid are not automatically renamed.
Rename Manually
A publisher can rename a class, enumeration, or non-member function in the library definition file.
Renaming C++ namespaces, the outer (enclosing) class for nested classes, member functions, data
members, enumerants, or the MATLAB package is not supported.
For example, MATLAB converts the class name _myclass in library mylib to x_myclass. To use the
class in MATLAB, type:
clib.mylib.x_myclass
To rename x_myclass, in the library definition file, change the name x_myclass to myClass, then
build the interface. When you use the class in MATLAB, type:
clib.mylib.myClass
clib.libName.className.(propertyName)
For example, suppose that you have interface clib.demo.MyClass with this property:
class MyClass
{
public:
int _mean;
};
x = clib.demo.MyClass;
xmean = x.('_mean')
This syntax is valid for names less than the maximum identifier length namelengthmax.
clib.libName.enumName.(enumMember)
5-43
5 Calling Functions in C++ Shared Libraries from MATLAB
For example, suppose that you have interface clib.enums.keywords with these properties:
EnumDefinition with properties:
var = clib.enums.keywords.('_class');
This syntax is valid for names less than the maximum identifier length namelengthmax.
5-44
Troubleshooting C++ Library Definition Issues
The C++ signature for function task does not have an argument inb.
void task(int* in, double* ind, int sz, char const* inc)
For more information about SHAPE values, see “Define Missing SHAPE Parameter” on page 5-28.
If you define the shape of argument ind as argument inc, MATLAB displays an error because a
string cannot be used for a numeric type.
defineArgument(taskDefinition, "ind", "clib.array.libname.Double", "input", "inc");
For more information about SHAPE values, see “Define Missing SHAPE Parameter” on page 5-28.
void task(int * in, double * ind, int sz, char const * inc)
5-45
5 Calling Functions in C++ Shared Libraries from MATLAB
If you already called the clibgen.generateLibraryDefinition function, you can edit the library
definition file definelibname.mlx to fix the build error. Search for the OutputFolder and
Libraries section and fill in or modify the libDef.Libraries variable. Be sure to specify the full
path and the library name. Save the file, then rerun the build function.
See Also
More About
• “Troubleshooting MATLAB Interface to C++ Library Issues” on page 5-47
• “Define Missing SHAPE Parameter” on page 5-28
• “Limitations to C/C++ Support” on page 5-40
5-46
Troubleshooting MATLAB Interface to C++ Library Issues
In some cases, a publisher might create a library interface that does not include classes or other
functionality from the original C++ library. For information about how to include missing
functionality in the MATLAB interface, see “How to Complete Definitions in Library Definition File”
on page 5-24.
For example, for library libname containing class MyClass, the clib array type is:
clib.array.libname.MyClass
For fundamental C++ types, use upper camel case for the element type name. For example, if the C+
+ type is double, then the clib array type is:
clib.array.libname.Double
For example, if the C++ type is signed int, then the MATLAB clib array type for library libname
is:
clib.array.libname.SignedInt
5-47
5 Calling Functions in C++ Shared Libraries from MATLAB
5-48
C++ to MATLAB Data Type Mapping
Numeric Types
Fixed-Width Integer Data Types
These type mappings are independent of platform and compiler. For integer types based on the
compiler, see “Non-Fixed-Width Integer Types” on page 5-49.
MATLAB supports these non-fixed-width C integer types. Based on the compiler used, MATLAB maps
these types to the corresponding fixed-width C types, as shown in the “Numeric Types Fixed-Width
Integer Data Types” on page 5-49 tables.
• short
• short int
• signed short
• signed short int
• unsigned short
• unsigned short int
• int
• signed int
• unsigned
• unsigned int
• long
• signed long
• signed long int
5-49
5 Calling Functions in C++ Shared Libraries from MATLAB
• unsigned long
• unsigned long int
• long long
This table shows how MATLAB data types correspond to std::vector types. By default, MATLAB
represents std::vector types with the MATLAB clib.array type. For more information, see
“MATLAB Object For C++ Arrays” on page 5-61.
For these types, specify DIRECTION as "input" and SHAPE as 1. For information about using
element types, see “MATLAB Object For C++ Arrays” on page 5-61.
5-50
C++ to MATLAB Data Type Mapping
5-51
5 Calling Functions in C++ Shared Libraries from MATLAB
5-52
C++ to MATLAB Data Type Mapping
MATLAB does not support these const and nonconst C++ return types.
5-53
5 Calling Functions in C++ Shared Libraries from MATLAB
bool Types
For these types, specify DIRECTION as "input" and SHAPE as 1.
class Set
{
public:
static int p1;
const static int p2;
};
int Set::p1 = 5;
const int Set::p2 = 10;
The help for clib.lib.Set shows p1 and p2 as properties. To use the properties in MATLAB:
res = 15
Do not update a static property by using the class name. If you do, then MATLAB creates a structure
named clib. You must manually clear the clib structure before calling any functions in the
interface. For example, if you try to update static property p1, then clib is a variable:
clib.lib.Set.p1 = 20
clib =
lib: [1×1 struct]
clear clib
clib.lib.Set.p1
ans = 5
5-54
C++ to MATLAB Data Type Mapping
For information about using static properties as SHAPE arguments, see “Use Property or Method as
SHAPE” on page 5-33.
User-Defined Types
Class and Struct Types
This table shows how to configure a C++ parameter type T in the definition file for a MATLAB
interface to library libname, where T is a class or a struct.
5-55
5 Calling Functions in C++ Shared Libraries from MATLAB
Enumerated Types
This table shows how to configure a C++ enum type T in the definition file for a MATLAB interface to
library libname, where T is an enumerated type.
5-56
C++ to MATLAB Data Type Mapping
MATLAB provides a clib.type.nullptr type so that you can pass NULL to a function with these C
++ input argument types:
• Pointers to objects. However, pointers to fundamental MATLAB array types are not supported.
• shared_ptr
• Arrays
The C++ interface returns type-specific empty values for functions that return nullptr.
When passing a void* input argument, MATLAB converts the underlying data to the corresponding C
++ type.
5-57
5 Calling Functions in C++ Shared Libraries from MATLAB
Type
5-58
C++ to MATLAB Data Type Mapping
• Any type with a size greater than 64 bits, for example long double
• References to a pointer, for example int*&
• Pointers or arrays of std::string
• Pointers or references to enumerations
• Reference data members
• void* data members
• Modifying static data members
• ** pointers, except:
• std::string
• std::wstring
• std::u16string
• std::u32string
• std::vector
• std::shared_ptr
• std::function
MATLAB reports on constructs that use unsupported types. To view these messages, use the
'Verbose' option in the clibgen.generateLibraryDefinition or clibgen.buildInterface
functions.
5-59
5 Calling Functions in C++ Shared Libraries from MATLAB
See Also
clibgen.generateLibraryDefinition | clibgen.buildInterface
More About
• “Define MATLAB Interface for C++ Library” on page 5-24
• “MATLAB Object For C++ Arrays” on page 5-61
5-60
MATLAB Object For C++ Arrays
A MATLAB clib array is only defined when the corresponding C++ native array or std::vector is
used by supported C++ constructs—function input and output arguments and data members. The
provided headers must contain the definition of the element type. The construct must be supported
by MATLAB and not dropped when building the interface.
myclassArray = clibArray('clib.libname.myclass',5);
e = myclassArray(1)
Alternatively, if the element type is a fundamental type, a user-defined class with a default
constructor, or a standard string type, call the clib.array constructor.
myclassArray = clib.array.libname.myclass(5)
To create an array from a fundamental type, you must know the element type. For more information,
see the “std::vector<T> Integer Types” on page 5-50 and std::vector<T> “Floating Point Types”
on page 5-50 tables in “C++ to MATLAB Data Type Mapping” on page 5-49. For example, if the C++
type is std::vector<int32_t>, then the MATLAB element type is clib.libname.Int. To create
an array with five elements, type:
myIntArray = clib.array.libname.Int(5)
To create an array from a standard string type, see the “std::vector<T> String Types” on page 5-53
table for element type information. For example, if the C++ type is std::vector<std::string>,
then the MATLAB element type is clib.libname.std.String. To create an array with five
elements, type:
myStringArray = clib.array.libname.std.String(5)
Note You cannot create an array of C++ objects using square brackets.
5-61
5 Calling Functions in C++ Shared Libraries from MATLAB
5-62
MATLAB Object For C++ Arrays
Memory Management
The memory for MATLAB arrays created with clibArray or clibConvertArray is owned by
MATLAB. To release the memory, call clibRelease.
See Also
clibArray | clibConvertArray | clibRelease
More About
• “C++ to MATLAB Data Type Mapping” on page 5-49
5-63
5 Calling Functions in C++ Shared Libraries from MATLAB
Handling Exceptions
MATLAB supports std::exception and its subclasses. MATLAB catches the std::exception
objects thrown from a library and displays text from the exception, if available.
5-64
Errors Parsing Header Files on macOS
Suppose that you have two header files. Header file simple1.hpp includes a standard header, such
as vector.
#ifndef SIMPLE1_HPP
#define SIMPLE1_HPP
#include <vector>
// class definitions
// functions
#endif
#include "simple1.hpp"
To include this content in the library, create a wrapper header file with the contents of simple1.hpp
and simple2.hpp. For example, create wrapsimple.hpp with these statements:
#ifndef SIMPLE1_HPP
#define SIMPLE1_HPP
#include <vector>
// class definitions
// functions
#endif
Create the library definition definesimple.mlx by using the wrapper header file.
clibgen.generateLibraryDefinition("wrapsimple.hpp","PackageName","simple")
See Also
clibgen.generateLibraryDefinition | clibgen.buildInterface
5-65
5 Calling Functions in C++ Shared Libraries from MATLAB
See Also
build
More About
• “Steps to Publish a MATLAB Interface to a C++ Library” on page 5-8
• “Define MATLAB Interface for C++ Library” on page 5-24
5-66
Lifetime Management of C++ Objects in MATLAB
Suppose that you have a function in library libname which takes ownership of the input argument.
void setInputObj(ObjClass *obj);
If you create the argument in MATLAB, then MATLAB owns the memory.
obj = clib.libname.ObjClass;
If you pass obj to setInputObj, then both MATLAB and setInputObj own the memory, which is
unsafe.
clib.libname.setInputObj(obj)
To transfer memory ownership to the library, modify the setInputObj definition in the library
definition file.
%setInputObjDefinition = addFunction(libnameDefinition, ...
% 'setInputObj(ObjClass * obj)', ...
%defineArgument(setInputObjDefinition,'obj','clib.libname.ObjClass',<DIRECTION>,<SHAPE>);
• For functions returning a pointer or a reference to an object, use the 'DeleteFcn' argument in
defineOutput (FunctionDefinition) or defineOutput (MethodDefinition).
For an example, see “Manage Memory of Returned Pointer or Reference” on page 5-68.
• For double pointer scalar output arguments, use the 'DeleteFcn' argument in
defineArgument (FunctionDefinition) or defineArgument (MethodDefinition).
For an example, see “Manage Memory of Double Pointer Input Argument” on page 5-68.
If you specify a library function for the deleter function, then that function is not included in the
interface and users cannot call the function from MATLAB. The MATLAB user calls the MATLAB
delete function, which calls the function specified by deleteFcn.
5-67
5 Calling Functions in C++ Shared Libraries from MATLAB
For more information, see “Memory Management for void* and void** Arguments” on page 5-88.
This example shows how to manage memory for functions returning a pointer or a reference to an
object. Suppose that you have a member function objFree that frees memory.
To use objFree when MATLAB deletes object ObjClass, modify the objCreate definition in the
library definition file.
%defineOutput(objCreateDefinition,'RetVal','clib.libname.ObjClass',<SHAPE>);
myObj = clib.libname.objCreate(x,y)
delete(myObj);
This example shows how to manage memory for an input argument of type void** configured as a
scalar output. This procedure applies to class objects as well. See parameter type T** in the “User-
Defined Types” on page 5-55 data mapping table.
Suppose that you have a member function clearTask that frees memory.
#include <cstdint>
typedef void* handle;
int32_t createTask (const char taskName[], handle *taskHandle);
void clearTask (handle taskHandle);
To allow MATLAB to take ownership of the void* object handle created by function createTask,
assign clearTask as a 'DeleteFcn' argument.
%defineArgument(createTaskDefinition, "taskHandle", "clib.lib.handle", "output", 1);
See Also
defineArgument (FunctionDefinition) | defineArgument (MethodDefinition) |
defineOutput (MethodDefinition) | defineOutput (FunctionDefinition)
5-68
Modify Library Help
This example shows help for the XMLPlatformUtils.Initialize method in the Apache Xerces-C+
+ XML parser library. This content comes from the Apache Xerces project, https://xerces.apache.org,
and is licensed under the Apache 2.0 license, https://www.apache.org/licenses/LICENSE-2.0.
To build a MATLAB interface to this library, you need the header files and shared library files. This
example describes the build process and shows the output of building such a library. You cannot,
however, execute the code shown in the example, unless you have access to the Xerces files.
Set Up
For information about setting up your environment, see “Requirements for Building Interface to C++
Libraries” on page 5-4.
• Verify your compiler. This example assumes the shared library file was built with the Microsoft
Visual C++® 2017 compiler.
• Identify the header files required for your interface. This example uses the
XMLPlatformUtils.Initialize method from the PlatformUtils.hpp file.
headers = includePath+"\xercesc\util\PlatformUtils.hpp";
• Edit the defineMyXercesLibrary.mlx file. This example resolves undefined functionality for
the Initialize method only. Search for:
• In the same method, define the panicHandler and memoryManager arguments as scalar by
replacing <SHAPE> with 1.
5-69
5 Calling Functions in C++ Shared Libraries from MATLAB
libDef = defineMyXercesLibrary
Description =
"clib.MyXercesLibrary.xercesc_3_1.XMLPlatformUtils.Initialize Method of C++ class xercesc_3_1::XMLPlatformUtils.
Perform per-process parser initialization"
DetailedDescription =
"This content is from the external library documentation.
• Modify the text This content is from the external library documentation to display
information about the Apache Xerces project. Open the library definition file.
edit defineMyXercesLibrary
• Search for the xercesc_3_1::XMLPlatformUtils::Initialize method:
libDef = defineMyXercesLibrary;
libDef.Classes(classID).Methods(methodID).DetailedDescription
ans =
"This content comes from the Apache Xerces project, https://xerces.apache.org, and
is licensed under the Apache 2.0 license, https://www.apache.org/licenses/LICENSE-2.0.
addPath(MyXercesLibrary)
5-70
Modify Library Help
• Update the system path, identifying the location myPath of your shared library file.
dllPath = "myPath\lib";
syspath = getenv("PATH");
setenv("PATH",dllPath+";"+syspath)
• Review the contents of your interface.
summary(defineMyXercesLibrary)
• Display help for the Initialize method.
help clib.MyXercesLibrary.xercesc_3_1.XMLPlatformUtils.Initialize
clib.MyXercesLibrary.xercesc_3_1.XMLPlatformUtils.Initialize Method of C++ class xercesc_3_1::XMLPlatformUtils.
Perform per-process parser initialization
This content comes from the Apache Xerces project, https://xerces.apache.org, and is licensed under the
Apache 2.0 license, https://www.apache.org/licenses/LICENSE-2.0.
Inputs
locale read-only string
locale The locale to use for messages.
panicHandler clib.MyXercesLibrary.xercesc_3_1.PanicHandler
panicHandler Application's panic handler, application owns this handler.
Application shall make sure that the plugged panic handler persists
through the call to XMLPlatformUtils::Terminate().
memoryManager clib.MyXercesLibrary.xercesc_3_1.MemoryManager
memoryManager Plugged-in memory manager which is owned by the
application. Applications must make sure that the
plugged-in memory manager persist through the call to
XMLPlatformUtils::Terminate()
No outputs
See Also
More About
• “Define MATLAB Interface for C++ Library” on page 5-24
• “Publish Help Text for MATLAB Interface to C++ Library” on page 5-20
5-71
5 Calling Functions in C++ Shared Libraries from MATLAB
#include <stack>
#ifdef _WIN32
#ifdef EXPORT
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#else
#define DLL_EXPORT __attribute__((visibility ("default")))
#endif
#endif
1 To run this example on Windows, create the Student.lib and Student.dll files from this
Student.cpp source file, using “Build Example Shared Library Files on Windows” on page 5-
79.
5-72
C++ Limitation Workaround Examples
#define EXPORT
#include "Student.hpp"
Student::Student() : rollNumber(0) {}
int Student::getRollNumber() {
return rollNumber;
}
#include <stack>
#include <stdexcept>
template<typename T>
class CStack {
std::stack<T> data;
public:
CStack() {}
5-73
5 Calling Functions in C++ Shared Libraries from MATLAB
};
#endif
4 Define a function readStudentsWrapper to call the readStudents function using the CStack
class and getStudentsWrapper to call the getStudents function. Include these functions in a
wrapper header file named StudentWrapper.hpp.
//Header to call readStudents and getStudents functions from MATLAB
#include "Student.hpp"
#include "CStack.hpp"
Ignore the Did not add messages. In MATLAB, you call functions readStudentsWrapper and
getStudentsWrapper instead of readStudents and getStudents. The constructor to class
CStack and member getData are used internally and are not callable from the interface.
6 Build the interface.
build(definestack)
addpath('stack')
7 Add the shared library path to the system (run-time) path. If the file is located on rtPath, then
type:
syspath = getenv('PATH');
rtPath = 'myrtpathname';
setenv('PATH',[rtPath ';' syspath]);
8 Call readStudentsWrapper.
studentsStack = clib.stack.CStack_Student_;
studentsStack.add(clib.stack.Student(1))
studentsStack.add(clib.stack.Student(2))
studentsStack.add(clib.stack.Student(3))
clib.stack.readStudentsWrapper(studentsStack)
9 Call getStudentsWrapper.
clear studentsStack;
studentsStack = clib.stack.getStudentsWrapper(3);
5-74
C++ Limitation Workaround Examples
1 To include the Pairs class, create this wrapper header file TemplatesWrapper.hpp. Assume
that Pairs supports int and double data types.
//Wrapper to instantiate template class Pairs
#include "Templates.hpp"
build(defineTemplates)
addpath('Templates')
4 Create Pairs objects and call the getVal1 and getVal2 functions.
Pairs1 = clib.Templates.Pairs_int_(2,3);
Val1 = Pairs1.getVal1;
Pairs2 = clib.Templates.Pairs_double_(4.5,10.9);
Val2 = Pairs2.getVal2;
Pairs3 = clib.Templates.Pairs_int_(4.3,10.9);
Val2 = Pairs3.getVal2;
5-75
5 Calling Functions in C++ Shared Libraries from MATLAB
Preprocessor Directives
A MATLAB interface to a C++ library does not support preprocessor directives (macros). For
example, this Area.hpp header file defines the macro PI. If you build a MATLAB interface, PI is not
included.
//Header with Macro preprocessor directive
#ifndef area_header
#define area_header
#ifdef _WIN32
#ifdef EXPORT
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#else
#define DLL_EXPORT __attribute__((visibility ("default")))
#endif
#define PI 3.1415
#endif
1 To run this example on Windows, create the Area.lib and Area.dll files from this Area.cpp
source file, using “Build Example Shared Library Files on Windows” on page 5-79.
#define EXPORT
#include "Area.hpp"
5-76
C++ Limitation Workaround Examples
7 Call getArea.
pi = clib.Area.getPI;
area = clib.Area.getArea(2,pi)
area =
12.5660
String Arrays
A MATLAB interface to a C++ library does not include functions with arguments std::string for
element type of vector. For example, the readStringVector and getStringVector functions in
this StringVector.hpp header file are not included when you build a MATLAB interface.
#ifdef _WIN32
#ifdef EXPORT
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#else
#define DLL_EXPORT __attribute__((visibility ("default")))
#endif
#endif
1 To run this example on Windows, create the StringVector.lib and StringVector.dll files
from this StringVector.cpp source file, using “Build Example Shared Library Files on
Windows” on page 5-79.
#define EXPORT
#include "StringVector.hpp"
5-77
5 Calling Functions in C++ Shared Libraries from MATLAB
3 To support std::vector of type std::string, create a CVector class, which defines these
methods to pass the std::vector between MATLAB and the library.
• Parameterized constructor:
CVector(std::vector<T>&& d) : data(std::move(d))
• Method to access the element at an index:
T get(int index)
• Method to add elements to vectors:
#include <vector>
template<typename T>
class CVector {
std::vector<T> data;
public:
CVector() {}
CVector(const std::vector<T>& d): data(d) {}
CVector(std::vector<T>&& d) : data(std::move(d)) {}
T get(int index) {
return data.at(index-1);
}
void add(const T& element) {
data.push_back(element);
}
const std::vector<T>& getData() const {
return data;
}
};
#endif
4 To include readStringVector and getStringVector, create a WrapperStringVector.hpp
header file, which defines methods to pass CVector arguments to the C++ library methods.
// Header that allows the readStringVector and getStringVector functions
// to be accessed from MATLAB interface
#include "StringVector.hpp"
#include "CVector.hpp"
#include <string>
5-78
C++ Limitation Workaround Examples
build(defineWrapperStringVector)
addpath('WrapperStringVector')
7 Add the shared library path to the system (run-time) path. If the file is located on rtPath, then
type:
syspath = getenv('PATH');
rtPath = 'myrtpathname';
setenv('PATH',[rtPath ';' syspath]);
8 Call the functions.
% Instantiate the CVector class
stringVectorObj = clib.StringVector.CVector_std____cxx11__basic_string_char_Std__char_traits_c;
mingwpath = 'mingwpathname';
set PATH=mingwpath;%PATH%
Run these commands to generate shared library from the source file source.cpp:
mingwpath\g++ -c source.cpp -o source.obj -std=c++11
mingwpath\g++ -shared -o source.dll source.obj -Wl,--out-implib,source.lib
See Also
More About
• “Limitations to C/C++ Support” on page 5-40
5-79
5 Calling Functions in C++ Shared Libraries from MATLAB
• Call C++ non-member functions in a parfor loop. A non-member function, sometimes called
package function, is defined outside of a class definition.
• Create C++ objects in a parfor iteration and use them in the same iteration.
• C++ objects created outside a parfor loop cannot be used in the parfor loop.
• C++ objects created in a parfor loop iteration cannot be used in another iteration or outside the
parfor loop.
Your C++ library might not be a candidate for parallel computing. Parfor loop iterations run in
different processes. If your code must run in the same process, then the result is not guaranteed.
See Also
parfor
5-80
Initialize Pointer Members of C++ Structures for MATLAB Interface to Library
struct S1 {
S1() {};
};
struct S2 {
S1 *s1;
S2() {};
};
Suppose that you built this code into library lib. When you try to reference pointer s1, it points to
random memory, which results in unpredictable behavior.
s2Obj = clib.lib.S2;
s2Obj.s1
To work around this issue, initialize the pointer inside the struct definition:
struct S1 {
S1() {};
};
struct S2 {
S1 *s1;
S2() {};
S1 s1 = S1(); // initialize pointer
};
See Also
5-81
5 Calling Functions in C++ Shared Libraries from MATLAB
sessionHandle = clib.lib.getHandle
sessionHandle =
SessionHandle is an opaque object.
You can pass the MATLAB sessionHandle variable to another function in the library:
clib.lib.closeHandle(sessionHandle)
See Also
5-82
Define void* and void** Arguments
You cannot create void* and void** types in MATLAB. Instead, you can use C++ library functions
with these types:
• If void* is defined with a typedef (or using) keyword, then MATLAB assigns the typedef
name as the MLTYPE.
• Publishers can assign a MATLAB type to a void* type by specifying MLTYPE in the library
definition file.
• MATLAB users can pass a void* return argument as input to a function that takes the
appropriate void* input.
MATLAB returns a void* return type for void** parameters. For more information, see “void**
Input Argument Types” on page 5-85.
If void* has a typedef defined in the library, MATLAB specifies MLTYPE as the new type name in
the typedef statement.
• If there is no typedef, chose a MATLAB type of the format clib.PackageName.TypeName, where
TypeName can include a namespace.
If the library does not have an appropriate typedef statement, you can define void* with a
MATLAB type.
This sample header file contains functions with void* types. You can define these types by using
statements from the generated library definition file for the example. Assumptions about the
argument types are based on the library documentation.
handle is defined by typedef. MATLAB creates the opaque type typedef void* handle.
5-83
5 Calling Functions in C++ Shared Libraries from MATLAB
MATLAB automatically uses this type to define MLTYPE as clib.libname.handle in the return
argument.
defineOutput(getHandleDefinition, "RetVal", "clib.lib.handle");
ghandle is defined with a using statement. As with handle in the previous example, MATLAB
automatically creates type typedef void* ghandle and uses it to define MLTYPE as
clib.libname.ghandle in the return argument.
ghandleDefinition = addOpaqueType(libnameDef, ...
"typedef void* ghandle", "MATLABName", ...
"clib.libname.ghandle", ...
"Description", "clib.libname.ghandle Representation of C++ type void*.")
defineOutput(getGHandleDefinition, "RetVal", "clib.libname.ghandle");
You can specify a new type, for example clib.libname.ImagData and use it to define RetVal as a
scalar value of this type.
defineOutput(getImagDataDefinition, "RetVal", "clib.libname.ImagData", 1);
Because there is a typedef for void* named data, you can use this to define RetVal as a scalar
value of type clib.libname.data.
defineOutput(getDataDefinition, "RetVal", "clib.libname.data", 1);
• Fundamental types
• clib.array types
• Types for C++ classes in the library
• void* typedef
Following are sample header file statements containing functions that have void* input arguments.
Assumptions about the argument types are based on the library documentation. The
defineArgument statements in the generated library definition file definelibname.mlx show you
how to treat each case.
5-84
Define void* and void** Arguments
The documentation for getAttribute indicates that void *value points to C++ data of
fundamental type uint64_t and that this value is passed as a return argument.
class TaskHandle;
int32 getAttribute(TaskHandle tHandle, int32 attribute, void *value);
You can define the readArray argument in this readRaw function as a clib.array type.
class TaskHandle;
int32 readRaw (TaskHandle tHandle, void *readArray, uInt32 arraySizeInBytes);
You can define the userdata argument in this setDrawCallback function as a class in the library.
void setDrawCallback(const String& winname,
OpenGlDrawCallback onOpenGlDraw,
void* userdata = 0)
void on_opengl(void* param) {
cv::ogl::Texture2D* backgroundTex = (cv::ogl::Texture2D*)param;
....
}
You can define the in argument in this setRemoteTimeout function by using an existing typedef
for void*.
typedef void* sessionHandle;
void setRemoteTimeout(sessionHandle in);
5-85
5 Calling Functions in C++ Shared Libraries from MATLAB
This sample header file contains functions with void** parameters. The following topics show you
how you can define these types by using statements from the generated library definition file for the
example. Assumptions about the argument types are based on the library documentation.
class HClass{};
typedef void* handle;
void getHandle(handle* out){
*out = new HClass();
}
using ghandle = void*;
void getGHandle(ghandle* out){
*out = new HClass();
}
The out argument in the getHandle function is defined as a pointer to the void* type handle. For
interface library lib, MATLAB uses the existing typedef statement to define out as an output
scalar of type clib.lib.handle.
defineArgument(getHandleDefinition, "out", "clib.lib.handle", "output", 1);
The out argument in the getGHandle function is defined as a pointer to the void* variable
ghandle defined by a using statement. MATLAB uses the existing using statement to define out as
an output scalar of type clib.lib.ghandle.
defineArgument(getGHandleDefinition, "out", "clib.lib.ghandle", "output", 1);
Because there is a typedef for void* named ptr, you can use this to define the out parameter as a
scalar value of type clib.lib.ptr.
5-86
Define void* and void** Arguments
For example, suppose that you create a library definition file definelib.mlx from this class A.
class A {
public:
typedef void* handle;
A(void* arg1, handle arg2) {}
void* task1() {
int* x = new int(10);
return x;
}
handle task2() {
int* x = new int(10);
return x;
}
};
MATLAB creates an opaque type for typedef void* handle and defines task2. The publisher
creates an opaque type clib.lib.A.NewHandle for void* task1 and the A class constructor
argument void* arg1.
addOpaqueType(libDef, "typedef void* A::handle", "MATLABName", "clib.lib.A.handle ", ...
"Description", "clib.lib.A.handle Representation of C++ opaque type.");
Because there is more than one void* input argument for constructor A, MATLAB displays this
message:
clib.lib.A(clib.lib.A.Newhandle,clib.lib.A.handle)
Note: This constructor cannot create object clib.lib.A, if object clib.lib.A.Newhandle/
clib.lib.A.handle is not available without constructing object of clib.lib.A.
Consider using a MATLABType which is outside the scope of clib.lib.A.
To create a clib.lib.A object for this constructor, specify MATLABType as one of these:
5-87
5 Calling Functions in C++ Shared Libraries from MATLAB
You can transfer ownership of the memory of a void* output to MATLAB by using the 'DeleteFcn'
name-value argument in defineOutput (FunctionDefinition) or defineOutput
(MethodDefinition). The deleter can be a user-defined function or the C++ standard delete
operator for void* return types.
For scalar void** output arguments, use the 'DeleteFcn' argument in defineArgument
(FunctionDefinition) or defineArgument (MethodDefinition). For an example, see
“Manage Memory of Double Pointer Input Argument” on page 5-68.
If you have multiple void* typedef statements, it is possible to define a deleter function that takes a
list of these typedef arguments as the MLTYPE for void* input. If you assign 'DeleteFcn' to only
one void* typedef returned by a function, then the MATLAB user cannot directly call this deleter
function by using that argument. MATLAB calls this function when the user calls the MATLAB
delete function. The user can, however, directly call the deleter function by using any of the other
void* typedef arguments.
For more information, see “Lifetime Management of C++ Objects in MATLAB” on page 5-67.
See Also
Related Examples
• “void* Argument Types” on page 5-57
• “Lifetime Management of C++ Objects in MATLAB” on page 5-67
5-88
Use Function Type Arguments
Function Types
• If a type in the library is declared in a typedef statement, then you can use it as a function type.
For example, suppose that you build this C++ code into an interface libname.
typedef void (*ACallback)(int pos, void *data);
int createTrackbar(const string& tname, ACallback onChange=0, void* data=0);
You can specify clib.libname.ACallback as a function type. The MATLAB signature for
createTrackbar is:
int32 clib.libname.createTrackbar(string tname, clib.libname.ACallback onChange, int32 data)
• If a type in the library is declared in a using statement, then you can use it as a function type. For
example, suppose that you build this C++ code into an interface libname.
You can specify clib.libname.funcPtrType as a function type. The MATLAB signature for
task is:
clib.libname.task(clib.array.libname.Int,clib.libname.funcPtrType)
clib.libname.task1(clib.type.libname.Function1)
clib.libname.task2(clib.type.libname.Function2)
You can use the double_inputoutput function defined in this header file to pass as input to
function type argument in callFunc_inputoutput to manipulate an array. You can do this by
creating a MATLAB function handle to double_inputoutput.
#include <functional>
void double_inputoutput( int * arr, int len){
for(int i=0;i<len;++i){
arr[i] = arr[i]*2;
}
}
5-89
5 Calling Functions in C++ Shared Libraries from MATLAB
help clib.test2.double_inputoutput
clib.test2.double_inputoutput Representation of C++ function double_inputoutput.
Inputs
arr int32
Outputs
arr int32
The MATLAB help function on function type displays a list of functions in your library that are
compatible with your function type .
help clib.test2.funcPtrType
Accepted input for clib.test2.funcPtrType is a handle to a C++ library function
with matching signature.
C++ library functions with matching inputs and outputs to the C++ function type:
@clib.test2.double_inputoutput
See Also
addFunctionType
5-90
Use Function and Member Function Templates
Overloaded Functions
MATLAB supports C++ function and member function templates. The C++ interface generates a
MATLAB function overload for each function template instantiation using a valid MATLAB name
based on the C++ function name. Suppose that you have this C++ header file that defines a function
template show and provides instantiations for types int, double, and const A.
Build interface libname, then display help for the show function. MATLAB displays the calling syntax
for three functions.
help clib.libname.show
Inputs
a int32
No outputs
Inputs
a double
No outputs
Inputs
a read-only clib.libname.A
No outputs
If you type:
var = pi;
clib.libname.show(var)
5-91
5 Calling Functions in C++ Shared Libraries from MATLAB
help clib.libname
Classes contained in clib.libname:
A - clib.libname.A Representation of C++ class A.
clib.libname.show_double_(var)
Publishers can modify these names when building an interface to the library. For more information,
see “Customize Function Template Names” on page 5-25.
5-92
Generate Interface
Generate Interface
This example shows how to create a MATLAB library definition file for the C++ library declared in
the header file matrixOperations.hpp and defined in the C++ source file
matrixOperations.cpp.
This example uses the MinGW64 Compiler (C++) for C++ language compilation.
Generated the definition file. MATLAB creates the definition file definematrixOperations.mlx.
clibgen.generateLibraryDefinition(fullfile(productPath,hppFile),...
"SupportingSourceFiles",fullfile(productPath,cppFile),...
"OverwriteExistingDefinitionFiles",true,...
"ReturnCArrays",false) % treat output as MATLAB arrays
To include the 5 undefined construct(s) in the interface, uncomment and complete the definitions in definematrixOperations.mlx.
To build the interface, call build(definematrixOperations).
MATLAB creates the definition file definematrixOperations.mlx. Click the link in the output
message to open the file, then continue with the next step.
See Also
clibgen.generateLibraryDefinition
5-93
5 Calling Functions in C++ Shared Libraries from MATLAB
Identify the shared library. Uncomment and execute one of these statements based on your selected
compiler.
%libPath = fullfile(productPath,"win64","mingw64");
%libPath = fullfile(productPath,"win64","microsoft");
Generate the definition file. MATLAB creates the definition file definematrixlib.mlx.
clibgen.generateLibraryDefinition(fullfile(hppPath,hppFile),...
"Libraries",fullfile(libPath,libFile),...
"PackageName",libname,...
"ReturnCArrays",false,... % treat output as MATLAB arrays
"OverwriteExistingDefinitionFiles",true,...
"Verbose",true)
Warning: Some C++ language constructs in the files for generating interface file are not supported and not imported.
To include the 5 undefined construct(s) in the interface, uncomment and complete the definitions in definematrixlib.mlx.
To build the interface, call build(definematrixlib).
See Also
clibgen.generateLibraryDefinition
5-94
Header File and Shared Object File on Linux
fullfile(matlabroot,"extern","examples","cpp_interface");
See Also
Related Examples
• “Header File and Import Library File on Windows” on page 5-10
• “Header File and Dynamic Shared Library File on macOS” on page 5-12
5-95
5 Calling Functions in C++ Shared Libraries from MATLAB
Generate the definition file. MATLAB creates the definition file definematrixlib.mlx.
clibgen.generateLibraryDefinition(fullfile(hppPath,hppFile),...
"Libraries", fullfile(libPath,libFile),...
"PackageName", libname,...
"ReturnCArrays",false,... % treat output as MATLAB arrays
"OverwriteExistingDefinitionFiles",true,...
"Verbose",true)
Warning: Some C++ language constructs in the files for generating interface file are not supported and not imported.
To include the 5 undefined construct(s) in the interface, uncomment and complete the definitions in definematrixlib.mlx.
To build the interface, call build(definematrixlib).
See Also
clibgen.generateLibraryDefinition
5-96
Generate Interface on macOS
Generate the definition file. MATLAB creates the definition file definematrixlib.mlx.
clibgen.generateLibraryDefinition(fullfile(hppPath,hppFile),...
"Libraries",fullfile(libPath,libFile),...
"PackageName",libname,...
"OverwriteExistingDefinitionFiles",true,... % delete existing definition files
"ReturnCArrays",false,... % treat output as MATLAB arrays
"Verbose",true)
Warning: Some C++ language constructs in the files for generating interface file are not supported and not imported.
To include the 5 undefined construct(s) in the interface, uncomment and complete the definitions in definematrixlib.mlx.
To build the interface, call build(definematrixlib).
See Also
clibgen.generateLibraryDefinition
5-97
5 Calling Functions in C++ Shared Libraries from MATLAB
To include the 5 undefined construct(s) in the interface, uncomment and complete the definitions in definematrixlib.mlx.
To build the interface, call build(definematrixlib).
Scroll through the library definition file open in your editor to find blocks of commented code for
these constructs.
MATLAB cannot automatically determine the size of arguments used by these functions.
Based on the documentation of the matrixOperations library, you can provide values for <SHAPE>
in the argument definition statements. For more information, see “Define Missing SHAPE Parameter”
on page 5-28.
5-98
Define Missing Constructs
See Also
5-99
5 Calling Functions in C++ Shared Libraries from MATLAB
To include the 5 undefined construct(s) in the interface, uncomment and complete the definitions in definematrixlib.mlx.
To build the interface, call build(definematrixlib).
Scroll through the library definition file open in your editor to find blocks of commented code for
these constructs.
MATLAB cannot automatically determine the size of arguments used by these functions.
Based on the documentation of the matrixOperations library, you can provide values for <SHAPE>
in the argument definition statements. For more information, see “Define Missing SHAPE Parameter”
on page 5-28.
5-100
Define Missing Constructs
See Also
5-101
5 Calling Functions in C++ Shared Libraries from MATLAB
To include the 5 undefined construct(s) in the interface, uncomment and complete the definitions
To build the interface, call build(definematrixlib).
Scroll through the library definition file open in your editor to find blocks of commented code for
these constructs.
MATLAB cannot automatically determine the size of arguments used by these functions.
Based on the documentation of the matrixOperations library, you can provide values for <SHAPE>
in the argument definition statements. For more information, see “Define Missing SHAPE Parameter”
on page 5-28.
5-102
Define Missing Constructs
See Also
5-103
5 Calling Functions in C++ Shared Libraries from MATLAB
To include the 5 undefined construct(s) in the interface, uncomment and complete the definitions in definematrixlib.mlx.
To build the interface, call build(definematrixlib).
Scroll through the library definition file open in your editor to find blocks of commented code for
these constructs.
MATLAB cannot automatically determine the size of arguments used by these functions.
Based on the documentation of the matrixOperations library, you can provide values for <SHAPE>
in the argument definition statements. For more information, see “Define Missing SHAPE Parameter”
on page 5-28.
5-104
Define Missing Constructs
See Also
Related Examples
• “Define Missing SHAPE Parameter” on page 5-28
5-105
5 Calling Functions in C++ Shared Libraries from MATLAB
Build Interface
definematrixlib;
View Functionality
If you defined all constructs in the definition file in the previous step, then the summary function
shows the complete library. In some cases, you might not define everything. Use summary to review
the library. If you need to make changes, return to the previous step to edit definematrixlib.
summary(definematrixlib)
MATLAB Interface to matrixlib Library
Class clib.matrixlib.Mat
Constructors:
clib.matrixlib.Mat(clib.matrixlib.Mat)
clib.matrixlib.Mat()
Methods:
setMat(clib.array.matrixlib.Int)
int32 getMat(uint64)
uint64 getLength()
copyMat(clib.array.matrixlib.Int)
No Properties defined
Functions
int32 clib.matrixlib.addMat(clib.matrixlib.Mat)
clib.matrixlib.updateMatByX(clib.matrixlib.Mat,int32)
clib.matrixlib.updateMatBySize(clib.matrixlib.Mat,clib.array.matrixlib.Int)
build(definematrixlib)
Building interface file 'matrixlibInterface.dll' for clib package 'matrixlib'.
Interface file 'matrixlibInterface.dll' built in folder 'C:\Users\Documents\MATLAB\matrixlib'.
To use the library, add the interface file folder to the MATLAB path.
addpath('C:\Users\Documents\MATLAB\matrixlib')
addpath('matrixlib')
Note You can repeat the generate, define, and build steps. However, once you display help for or call
functions in the library, you cannot update the definematrixlib definition file in the same MATLAB
session. Either restart MATLAB or create a new definition file by using the 'PackageName' name-
value argument for the clibgen.generateLibraryDefinition function.
5-106
Build Interface
See Also
5-107
5 Calling Functions in C++ Shared Libraries from MATLAB
Build Interface
definematrixlib;
View Functionality
If you defined all constructs in the definition file in the previous step, then the summary function
shows the complete library. In some cases, you might not define everything. Use summary to review
the library. If you need to make changes, return to the previous step to edit definematrixlib.
summary(definematrixlib)
MATLAB Interface to matrixlib Library
Class clib.matrixlib.Mat
Constructors:
clib.matrixlib.Mat(clib.matrixlib.Mat)
clib.matrixlib.Mat()
Methods:
setMat(clib.array.matrixlib.Int)
int32 getMat(uint64)
uint64 getLength()
copyMat(clib.array.matrixlib.Int)
No Properties defined
Functions
int32 clib.matrixlib.addMat(clib.matrixlib.Mat)
clib.matrixlib.updateMatByX(clib.matrixlib.Mat,int32)
clib.matrixlib.updateMatBySize(clib.matrixlib.Mat,clib.array.matrixlib.Int)
build(definematrixlib)
Building interface file 'matrixlibInterface.so' for clib package 'matrixlib'.
Interface file 'matrixlibInterface.dylib' built in folder '/home/Documents/MATLAB/matrixlib'.
To use the library, add the interface file folder to the MATLAB path.
addpath('/home/Documents/MATLAB/matrixlib')
addpath('matrixlib')
Note You can repeat the generate, define, and build steps. However, once you display help for or call
functions in the library, you cannot update the definematrixlib definition file in the same MATLAB
session. Either restart MATLAB or create a new definition file by using the 'PackageName' name-
value argument for the clibgen.generateLibraryDefinition function.
5-108
Build Interface
See Also
5-109
5 Calling Functions in C++ Shared Libraries from MATLAB
Build Interface
definematrixlib;
View Functionality
If you defined all constructs in the definition file in the previous step, then the summary function
shows the complete library. In some cases, you might not define everything. Use summary to review
the library. If you need to make changes, return to the previous step to edit definematrixlib.
summary(definematrixlib)
MATLAB Interface to matrixlib Library
Class clib.matrixlib.Mat
Constructors:
clib.matrixlib.Mat(clib.matrixlib.Mat)
clib.matrixlib.Mat()
Methods:
setMat(clib.array.matrixlib.Int)
int32 getMat(uint64)
uint64 getLength()
copyMat(clib.array.matrixlib.Int)
No Properties defined
Functions
int32 clib.matrixlib.addMat(clib.matrixlib.Mat)
clib.matrixlib.updateMatByX(clib.matrixlib.Mat,int32)
clib.matrixlib.updateMatBySize(clib.matrixlib.Mat,clib.array.matrixlib.Int)
build(definematrixlib)
Building interface file 'matrixlibInterface.so' for clib package 'matrixlib'.
Interface file 'matrixlibInterface.so' built in folder '/home/Documents/MATLAB/matrixlib'.
To use the library, add the interface file folder to the MATLAB path.
addpath('/home/Documents/MATLAB/matrixlib')
addpath('matrixlib')
Note You can repeat the generate, define, and build steps. However, once you display help for or call
functions in the library, you cannot update the definematrixlib definition file in the same MATLAB
session. Either restart MATLAB or create a new definition file by using the 'PackageName' name-
value argument for the clibgen.generateLibraryDefinition function.
5-110
Build Interface
See Also
5-111
5 Calling Functions in C++ Shared Libraries from MATLAB
definematrixOperations;
View Functionality
If you defined all constructs in the definition file in the previous step, then the summary function
shows the complete library. In some cases, you might not define everything. Use summary to review
the library. If you need to make changes, return to the previous step to edit
definematrixOperations.
summary(definematrixOperations)
Class clib.matrixOperations.Mat
Constructors:
clib.matrixOperations.Mat(clib.matrixOperations.Mat)
clib.matrixOperations.Mat()
Methods:
setMat(clib.array.matrixOperations.Int)
int32 getMat(uint64)
uint64 getLength()
copyMat(clib.array.matrixOperations.Int)
No Properties defined
Functions
int32 clib.matrixOperations.addMat(clib.matrixOperations.Mat)
clib.matrixOperations.updateMatByX(clib.matrixOperations.Mat,int32)
clib.matrixOperations.updateMatBySize(clib.matrixOperations.Mat,clib.array.matrixOperations.Int)
build(definematrixOperations)
To use the library, add the interface file folder to the MATLAB path.
addpath('C:\Users\Documents\MATLAB\matrixOperations')
addpath('matrixOperations')
Note You can repeat the generate, define, and build steps. However, once you display help for or call
functions in the library, you cannot update the definition file in the same MATLAB session. Either
restart MATLAB or create a new definition file by using the 'PackageName' name-value argument
for the clibgen.generateLibraryDefinition function.
5-112
Build Interface to matrixoperations Library
See Also
build | summary
5-113
5 Calling Functions in C++ Shared Libraries from MATLAB
To use the library, add the interface file folder to the MATLAB path.
addpath('C:\Users\Documents\MATLAB\matrixlib')
syspath = split(getenv('PATH'),';')
addpath('matrixlib')
View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.
To display signatures for the package functions, click the links for addMat, updateMatByX, and
updateMatBySize.
To display information about class clib.matrixlib.Mat, click the link for Mat.
5-114
Call Library Functions on Windows
See Also
Related Examples
• “Set Run-Time Library Path for C++ Interface” on page 5-6
5-115
5 Calling Functions in C++ Shared Libraries from MATLAB
Start MATLAB in the same system prompt where you set the LD_LIBRARY_PATH variable.
syspath = split(getenv('LD_LIBRARY_PATH'),';')
addpath('matrixlib')
View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.
To display signatures for the package functions, click the links for addMat, updateMatByX, and
updateMatBySize.
To display information about class clib.matrixlib.Mat, click the link for Mat.
5-116
Call Library Functions on Linux
See Also
5-117
5 Calling Functions in C++ Shared Libraries from MATLAB
Start MATLAB in the same system prompt where you set the DYLD_LIBRARY_PATH variable.
syspath = split(getenv('DYLD_LIBRARY_PATH'),';')
addpath('matrixlib')
View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.
To display signatures for the package functions, click the links for addMat, updateMatByX, and
updateMatBySize.
To display information about class clib.matrixlib.Mat, click the link for Mat.
5-118
Call Library Functions on macOS
See Also
5-119
5 Calling Functions in C++ Shared Libraries from MATLAB
To use the library, add the interface file folder to the MATLAB path.
addpath('C:\Users\Documents\MATLAB\matrixOperations')
View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.
To display signatures for the package functions, click the links for addMat, updateMatByX, and
updateMatBySize.
To display information about class clib.matrixOperations.Mat, click the link for Mat.
See Also
5-120
Generate Interface to school Library
Generate the library definition file. MATLAB creates the definition file defineschool.mlx.
clibgen.generateLibraryDefinition(fullfile(productPath,hppFile),...
"OverwriteExistingDefinitionFiles",true)
See Also
clibgen.generateLibraryDefinition
5-121
5 Calling Functions in C++ Shared Libraries from MATLAB
Constructs with missing information are commented out. Scroll through the file to locate the section
titled "C++ function getName with MATLAB name clib.school.getName". Uncomment the statements
in the getName code section.
The input argument p is a scalar value. Replace <SHAPE> in this statement with the number 1:
defineArgument(getNameDefinition, "p", "clib.school.Person", "input", <SHAPE>);
See Also
Related Examples
• “Define Missing SHAPE Parameter” on page 5-28
5-122
Build Interface to school Library
View Functionality
If you defined all constructs in the definition file in the previous step, then the summary function
shows the complete library. In some cases, you might not define everything. Use summary to review
the library. If you need to make changes, return to the previous step to edit defineschool.
summary(defineschool)
Class clib.school.Person
Constructors:
clib.school.Person()
clib.school.Person(string,uint64)
clib.school.Person(clib.school.Person)
Methods:
setName(string)
setAge(uint64)
string getName()
uint64 getAge()
No Properties defined
Class clib.school.Teacher
Constructors:
clib.school.Teacher()
clib.school.Teacher(string,uint64)
clib.school.Teacher(clib.school.Teacher)
Methods:
string getName()
No Properties defined
Class clib.school.Student
Constructors:
clib.school.Student()
clib.school.Student(string,uint64)
clib.school.Student(clib.school.Student)
Methods:
string getName()
5-123
5 Calling Functions in C++ Shared Libraries from MATLAB
No Properties defined
Functions
string clib.school.getName(clib.school.Person)
build(defineschool)
To use the library, add the interface file folder to the MATLAB path.
addpath('C:\Users\Documents\MATLAB\school')
Add the library to your path. Either click the link in the message or type:
addpath('school')
Note You can repeat the generate, define, and build steps. However, once you display help for or call
functions in the library, you cannot update the defineschool definition file or rebuild in the same
MATLAB session. Either restart MATLAB or create a new definition file by using the 'PackageName'
name-value argument for the clibgen.generateLibraryDefinition function.
See Also
build | summary
5-124
Call school Library Functions
View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.
Note Once you use a library class or function, you cannot modify the library definition unless you
restart MATLAB and rebuild the library.
t1 = clib.school.Teacher('Ms. Jones',24);
getName(t1)
Distribute Interface
To give the interface to another MATLAB user, instruct them to add the schoolInterface.dll file
to a folder named school and add the folder to the MATLAB path. The package name is
clib.school.
See Also
5-125
6
A shared library needs a header file, which provides signatures for the functions in the library. A
function signature, or prototype, establishes the name of the function and the number and types of its
parameters. Specify the full path of the shared library and its header file.
You need an installed MATLAB-supported C compiler. For an up-to-date list of supported compilers,
see Supported and Compatible Compilers.
MATLAB accesses C routines built into external, shared libraries through a command-line interface.
This interface lets you load an external library into MATLAB memory and access functions in the
library. Although types differ between the two language environments, usually you can pass types to
the C functions without converting. MATLAB converts for you.
If the library function passes arguments, you need to determine the data type passed to and from the
function. For information about data, see these topics.
When you are finished working with the shared library, it is important to unload the library to free
memory.
See Also
loadlibrary | calllib | libfunctions
More About
• “C and MATLAB Equivalent Types” on page 6-13
• “Limitations to Shared Library Support” on page 6-6
6-2
Invoke Library Functions
calllib('libname','funcname',arg1,...,argN)
Specify the library name, function name, and, if required, any arguments that get passed to the
function.
See Also
More About
• “Pass Arguments to Shared C Library Functions” on page 6-13
6-3
6 Calling Functions in C Shared Libraries from MATLAB
To view function signatures, use the -full switch. This option shows the MATLAB syntax for calling
functions written in C. The types used in the parameter lists and return values are MATLAB types, not
C types. For more information on types, see “C and MATLAB Equivalent Types” on page 6-13.
To display information about library functions in a separate window, use the libfunctionsview
function. MATLAB displays the following information:
Heading Description
Return Type Types the method returns
Name Function name
Arguments Valid types for input arguments
See Also
More About
• “C and MATLAB Equivalent Types” on page 6-13
6-4
Load and Unload Library
To load a shared library into MATLAB, use the loadlibrary function. The most common syntax is:
loadlibrary('shrlib','hfile')
where shrlib is the shared library file name, and hfile is the name of the header file containing
the function prototypes.
Note The header file provides signatures for the functions in the library and is a required argument
for loadlibrary.
When you are finished working with the shared library, it is important to unload the library to free
memory.
See Also
loadlibrary | unloadlibrary
6-5
6 Calling Functions in C Shared Libraries from MATLAB
Many noncommercial libraries or libraries that have only been tested from C++ have interfaces that
are not usable and require modification or an interface layer. In this case, we recommend using MEX
files.
Bit Fields
You can modify a bit field declaration by using type int or an equivalent. For example, if your library
has the following declared in its header file:
int myfunction();
struct mystructure
{
/* note the sum of fields bits */
unsigned field1 :4;
unsigned field2 :4;
};
6-6
Limitations to Shared Library Support
int myfunction();
struct mystructure
{
/* field 8 bits wide to be manipulated in MATLAB */
/* A char is 8 bits on all supported platforms */
char allfields;
};
After editing the source code, rebuild the library. It is then possible to access the data in the two
fields using bit masking in MATLAB.
Enum Declarations
char definitions for enum are not supported. In C, a char constant, for example 'A', is automatically
converted to its numeric equivalent (65). MATLAB does not convert constants. To use this type of
enum, edit the header file by replacing 'A' with the number 65 (int8('A') == 65). For example,
replace:
with:
struct mystruct
{
union
{
struct {char byte1,byte2;};
short word;
};
};
with:
struct mystruct
{
short word;
};
6-7
6 Calling Functions in C Shared Libraries from MATLAB
Compiler Dependencies
Header files must be compatible with the supported compilers on a platform. For an up-to-date list of
supported compilers, see Supported and Compatible Compilers. You cannot load external libraries
with explicit dependencies on other compilers.
The shared library interface does not support library functions that work with function pointers.
Multilevel Pointers
Limited support for multilevel pointers and structures containing pointers. Using inputs and outputs
and structure members declared with more than two levels of indirection is unsupported. For
example, double ***outp translated to doublePtrPtrPtr is not supported.
You can create multiple alias functions in a prototype file, one for each set of arguments used to call
the function. For more information, see “MATLAB Prototype Files” on page 6-39.
See Also
More About
• “Limitations Using Structures” on page 6-9
6-8
Limitations Using Structures
• Every MATLAB field name must match a field name in the library structure definition.
• MATLAB structures cannot contain fields that are not in the library structure definition.
• If a MATLAB structure contains fewer fields than defined in the library structure, MATLAB sets
undefined fields to zero.
• Field names are case-sensitive. For example, suppose that library mylib contains function
myfunc with the following structure definition.
struct S {
double len;
};
The field name is len. If you pass a structure to myfunc with the field name Len, MATLAB
displays an error.
S.Len = 100;
calllib('mylib','myfunc',S)
struct S {
double Num;
double num;
};
See Also
More About
• “Limitations to Shared Library Support” on page 6-6
6-9
6 Calling Functions in C Shared Libraries from MATLAB
or
There was an error loading the library "/home/myname/testlib.so"
'/home/myname/mylibs/testlib.so' has different architecture than the host.
If the library has dependencies which MATLAB cannot find, then MATLAB displays messages as
described in “Invalid MEX File Errors” on page 7-55.
To find library dependencies on Windows systems, use the third-party product Dependency Walker.
This free utility scans Windows modules and builds a hierarchical tree diagram of all dependent
modules. For each module found, it lists all the functions exported by that module, and which of those
functions are called by other modules. See How do I determine which libraries my MEX-file or stand-
alone application requires? for information on using the Dependency Walker.
6-10
No Matching Signature Error
For example, the function signature for the addStructByRef function in shrlibsample is:
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
struct.p1 = 4;
struct.p2 = 7.3;
struct.p3 = -290;
If you call the function without the input argument, MATLAB displays the error message.
[res,st] = calllib('shrlibsample','addStructByRef')
[res,st] = calllib('shrlibsample','addStructByRef',struct)
See Also
calllib | libfunctions
6-11
6 Calling Functions in C Shared Libraries from MATLAB
If your library uses a different calling convention, create a loadlibrary prototype file and modify it
with the correct settings, as described in MATLAB Answers™ article Why does MATLAB crash when I
make a function call on a DLL in MATLAB 7.6 (R2008a)?
See Also
loadlibrary
More About
• “MATLAB Prototype Files” on page 6-39
External Websites
• Calling Conventions
6-12
Pass Arguments to Shared C Library Functions
In this section...
“C and MATLAB Equivalent Types” on page 6-13
“How MATLAB Displays Function Signatures” on page 6-14
“NULL Pointer” on page 6-15
“Manually Convert Data Passed to Functions” on page 6-15
The following table shows how MATLAB maps C pointers (column 1) to the equivalent MATLAB
function signature (column 2). Usually, you can pass a variable from the Equivalent MATLAB Type
column to functions with the corresponding Argument Data Type. See “Pointer Arguments in C
Functions” on page 6-35 for information about when to use a lib.pointer object instead.
6-13
6 Calling Functions in C Shared Libraries from MATLAB
• Many arguments (like int32 and double) are similar to their C counterparts. In these cases, pass
in the MATLAB types shown for these arguments.
• Some C arguments (for example, **double, or predefined structures), are different from
standard MATLAB types. In these cases, either pass a standard MATLAB type and let MATLAB
convert it for you, or convert the data yourself using the MATLAB functions libstruct and
libpointer. For more information, see “Manually Convert Data Passed to Functions” on page 6-
15.
• C functions often return data in input arguments passed by reference. MATLAB creates additional
output arguments to return these values. Input arguments ending in Ptr or PtrPtr are also listed
as outputs.
For an example of MATLAB function signatures, see “Shared Library shrlibsample” on page 6-17.
6-14
Pass Arguments to Shared C Library Functions
NULL Pointer
You can create a NULL pointer to pass to library functions in the following ways:
To create an empty libstruct object, call libstruct with only the structtype argument. For
example:
sci = libstruct('c_struct')
get(sci)
p1: 0
p2: 0
p3: 0
• When passing the same data to a series of library functions, convert it once manually before
calling the first function rather than having MATLAB convert it automatically on every call. This
strategy reduces the number of unnecessary copy and conversion operations.
• When passing large structures, save memory by creating MATLAB structures that match the
shape of the C structures used in the function instead of using generic MATLAB structures. The
libstruct function creates a MATLAB structure modeled from a C structure taken from the
library.
6-15
6 Calling Functions in C Shared Libraries from MATLAB
• When an argument to an external function uses more than one level of referencing (for example,
double **), pass a pointer created using the libpointer function rather than relying on
MATLAB to convert the type automatically.
See Also
libstruct | libpointer | libfunctions | libfunctionsview
Related Examples
• “Shared Library shrlibsample” on page 6-17
More About
• “Represent Structure Arguments in C Shared Library Functions” on page 6-37
6-16
Shared Library shrlibsample
edit([matlabroot '/extern/examples/shrlib/shrlibsample.c'])
edit([matlabroot '/extern/examples/shrlib/shrlibsample.h'])
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
• Make the folder your current working folder:
cd(fullfile(matlabroot,'extern','examples','shrlib'))
Load the library and display the MATLAB signatures for the functions in the library.
loadlibrary('shrlibsample')
libfunctions shrlibsample -full
6-17
6 Calling Functions in C Shared Libraries from MATLAB
stringToUpper Function
The stringToUpper function in the shrlibsample library converts the characters in the input
argument to uppercase. The input parameter, char *, is a C pointer to a string.
if (p != NULL)
while (*p!=0)
*p++ = toupper(*p);
return input;
}
The function signature for stringToUpper is shown in the following table. MATLAB maps the C
pointer type (char *) into cstring so you can pass a MATLAB character array to the function.
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
res = calllib('shrlibsample','stringToUpper',str)
res =
'THIS WAS A MIXED CASE STRING'
The input parameter is a pointer to type char. However, a MATLAB character array is not a pointer,
so the stringToUpper function does not modify the input argument, str.
str
6-18
Pass String Arguments Examples
str =
'This was a Mixed Case string'
See Also
Related Examples
• “Shared Library shrlibsample” on page 6-17
• “Iterate Through lib.pointer Object” on page 6-33
6-19
6 Calling Functions in C Shared Libraries from MATLAB
struct c_struct {
double p1;
short p2;
long p3;
};
Both functions sum the values of the fields in the structure. The input to addStructFields is
c_struct. The input to addStructByRef is a pointer to c_struct. This function also modifies the
fields after summing the values.
addStructFields Function
The addStructFields function sums the values of the fields in a c_struct structure.
addStructByRef Function
The addStructByRef function sums the values of the fields in a c_struct structure, then modifies
the fields. The function returns the sum calculated before modifying the fields.
6-20
Pass Structures Examples
Since the function modifies the input argument, MATLAB also returns the input as an output
argument of type c_structPtr. The MATLAB function signature is:
You can pass a MATLAB structure to the function and let MATLAB autoconvert the argument. Or you
can pass a pointer to a structure, which avoids creating a copy of the structure.
Call the function. MATLAB automatically converts the fields of structure sm to the library definition
for c_struct.
calllib('shrlibsample','addStructFields',sm)
ans = 1177
Convert the fields, which are of type double, to match the c_struct structure types, double,
short, and long.
6-21
6 Calling Functions in C Shared Libraries from MATLAB
sc = libstruct('c_struct',sm);
get(sc)
p1: 476
p2: -299
p3: 1000
calllib('shrlibsample','addStructFields',sc)
ans = 1177
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
Create a structure.
S.p1 = 476;
S.p2 = -299;
S.p3 = 1000;
Call addStructByRef.
res = calllib('shrlibsample','addStructByRef',S)
res = 1177
MATLAB does not modify the contents of structure S, since it is not a pointer.
6-22
Pass Structures Examples
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
S.p1 = 20;
S.p2 = 99;
S.p3 = 3;
sp = libpointer('c_struct',S);
sp.Value
res = calllib('shrlibsample','addStructByRef',sp)
res = 122
When you pass a pointer, the function modifies the fields in the structure it points to.
sp.Value
See Also
libstruct | libpointer
Related Examples
• “Shared Library shrlibsample” on page 6-17
More About
• “Strategies for Passing Structures” on page 6-37
• “Limitations Using Structures” on page 6-9
6-23
6 Calling Functions in C Shared Libraries from MATLAB
readEnum Function
The readEnum function in the shrlibsample library displays a string that matches the input
argument.
switch (val) {
case en1: return outputs[0];
case en2: return outputs[1];
case en4: return outputs[2];
default : return outputs[3];
}
return outputs[4];
}
The values for the Enum1 input are defined in the shrlibsample.h header file.
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
In MATLAB, you can express an enumerated type as either the enumeration string or its equivalent
numeric value. Call readEnum with a string argument.
calllib('shrlibsample','readEnum','en4')
6-24
Pass Enumerated Types Examples
ans =
'You chose en4'
Call readEnum with the equivalent numeric argument. The Enum1 definition declares enumeration
en4 equal to 4.
calllib('shrlibsample','readEnum',4)
ans =
'You chose en4'
See Also
Related Examples
• “Shared Library shrlibsample” on page 6-17
6-25
6 Calling Functions in C Shared Libraries from MATLAB
multDoubleRef Function
The multDoubleRef function in the shrlibsample library multiplies the input by 5.
EXPORTED_FUNCTION double *multDoubleRef(double *x)
{
*x *= 5;
return x;
}
The input is a pointer to a double, and the function returns a pointer to a double. The MATLAB
function signature is:
Value: 13.3000
DataType: 'doublePtr'
6-26
Pass Pointers Examples
calllib('shrlibsample','multDoubleRef',Xptr);
Xptr.Value
ans = 66.5000
Xptr is a handle object. Copies of this handle refer to the same underlying object and any operations
you perform on a handle object affect all copies of that object. However, Xptr is not a C language
pointer. Although it points to X, it does not contain the address of X. The function modifies the Value
property of Xptr but does not modify the value in the underlying object X. The original value of X is
unchanged.
X = 13.3000
X = 1:10;
xp = libpointer('doublePtr',X);
xp.Value
ans = 1×10
1 2 3 4 5 6 7 8 9 10
Use the lib.pointer plus operator (+) to create a pointer to the last six elements of X.
xp2 = xp + 4;
xp2.Value
ans = 1×6
5 6 7 8 9 10
Multilevel Pointers
Multilevel pointers are arguments that have more than one level of referencing. A multilevel pointer
type in MATLAB uses the suffix PtrPtr. For example, use doublePtrPtr for the C argument
double **.
When calling a function that takes a multilevel pointer argument, use a lib.pointer object and let
MATLAB convert it to the multilevel pointer.
6-27
6 Calling Functions in C Shared Libraries from MATLAB
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
sp = libpointer('c_structPtr');
res = calllib('shrlibsample','allocateStruct',sp)
calllib('shrlibsample','deallocateStruct',sp)
char** acquireString(void)
6-28
Pass Pointers Examples
The following pseudo-code shows how to manipulate the return value, an array of pointers to
strings.
ptr = calllib(myLib,'acquireString')
MATLAB creates a lib.pointer object ptr of type stringPtrPtr. This object points to the first
string. To view other strings, increment the pointer. For example, to display the first three strings,
type:
ans =
'str1'
ans =
'str2'
ans =
'str3'
See Also
libpointer
6-29
6 Calling Functions in C Shared Libraries from MATLAB
print2darray Function
The print2darray function in the shrlibsample library displays the values of a 2-D array with
three columns and a variable number of rows. The my2d parameter is a two-dimensional array of
double. The len parameter is the number of rows.
EXPORTED_FUNCTION void print2darray(double my2d[][3],int len)
{
int indxi,indxj;
for(indxi=0;indxi<len;++indxi)
{
for(indxj=0;indxj<3;++indxj)
{
mexPrintf("%10g",my2d[indxi][indxj]);
}
mexPrintf("\n");
}
}
m = 4×3
1 5 9
2 6 10
3 7 11
4 8 12
6-30
Pass Arrays Examples
1 2 3
4 5 6
7 8 9
10 11 12
calllib('shrlibsample','print2darray',m',4)
1 5 9
2 6 10
3 7 11
4 8 12
multDoubleArray Function
The multDoubleArray function in the shrlibsample library multiplies each element of an array by
three. The function uses a single subscript (linear indexing) to navigate the input array.
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
vin = reshape(1:20,2,5,2);
vs = size(vin)
vs = 1×3
2 5 2
6-31
6 Calling Functions in C Shared Libraries from MATLAB
Call multDoubleArray to multiply each element. Display the dimensions of the output.
vout = calllib('shrlibsample','multDoubleArray',vin,20);
size(vout)
ans = 1×2
2 10
vout = reshape(vout,vs);
size(vout)
ans = 1×3
2 5 2
6-32
Iterate Through lib.pointer Object
In this section...
“Create Cell Array from lib.pointer Object” on page 6-33
“Perform Pointer Arithmetic on Structure Array” on page 6-34
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
Call the getListOfStrings function to create an array of character vectors. The function returns a
pointer to the array.
ptr = calllib('shrlibsample','getListOfStrings');
class(ptr)
ans =
'lib.pointer'
Create indexing variables to iterate through the arrays. Use ptrindex for the array returned by the
function and index for the MATLAB array.
ptrindex = ptr;
index = 1;
Create the cell array of character vectors mlStringArray. Copy the output of getListOfStrings
to the cell array.
mlStringArray
6-33
6 Calling Functions in C Shared Libraries from MATLAB
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
s = struct('p1',{1,2,3},'p2',{1.1,2.2,3.3},'p3',{0});
sptr = libpointer('c_struct',s);
v1 = sptr.Value
sptr = sptr + 1;
v2 = sptr.Value
6-34
Represent Pointer Arguments in C Shared Library Functions
Often, you can simply pass a MATLAB variable (passing an argument by value), even when the
signature for that function declares the argument to be a pointer. There are times, however, when it
is useful to pass a lib.pointer.
The syntax [int8(str) 0] creates the null-terminated string required by the C function. To read
the string, and verify the pointer type, enter:
char(vp.Value)
vp.DataType
ans =
string variable
ans =
voidPtr
MATLAB automatically converts an argument passed by value into an argument passed by reference
when the external function prototype defines the argument as a pointer. Call a function that takes a
voidPtr to a string as an input argument using the following syntax.
func_name([int8(str) 0])
Although MATLAB converts the argument from a value to a pointer, it must be of the correct type.
6-35
6 Calling Functions in C Shared Libraries from MATLAB
short buffer[99]
BufferSize = 99;
pBuffer = libpointer('int16Ptr',zeros(BufferSize,1));
calllib('myLib','AcquireData,BufferSize,pbuffer)
while (~calllib('myLib','IsAcquisitionDone')
pause(0.1)
end
result = pBuffer.Value;
When the library is done with the buffer, clear the MATLAB variable:
clear pBuffer
See Also
lib.pointer
6-36
Represent Structure Arguments in C Shared Library Functions
• Every MATLAB field name must match a field name in the library structure definition. Field names
are case-sensitive.
• MATLAB structures cannot contain fields that are not in the library structure definition.
• If a MATLAB structure contains fewer fields than defined in the library structure, MATLAB sets
undefined fields to zero.
You do not need to match the data types of numeric fields. The calllib function converts to the
correct numeric type.
However, when working with repeated calls that pass large structures, convert the structure
manually before making any calls to external functions. You save processing time by converting the
structure data only once at the start rather than at each function call. You can also save memory if
the fields of the converted structure take up less space than the original MATLAB structure.
To convert manually, call the libstruct function to create a libstruct object. Although it is an object,
it behaves like a MATLAB structure. The fields of the object are derived from an externally specified
structure type.
See Also
libstruct
Related Examples
• “Add Values of Fields in Structure” on page 6-21
• “Preconvert MATLAB Structure Before Adding Values” on page 6-21
More About
• “Limitations Using Structures” on page 6-9
6-37
6 Calling Functions in C Shared Libraries from MATLAB
if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
Create the libstruct object. Object sc is an instance of a MATLAB class called lib.c_struct.
sc = libstruct('c_struct')
sc =
lib.c_struct
set(sc,'p1',100,'p2',150,'p3',200)
get(sc)
p1: 100
p2: 150
p3: 200
sc.p1 = 23;
get(sc)
p1: 23
p2: 150
p3: 200
6-38
MATLAB Prototype Files
Like a header file, the prototype file contains the function signatures for the library. Here are some
reasons for using a prototype file.
You can change the prototypes by editing the prototype file and reloading the library.
6-39
6 Calling Functions in C Shared Libraries from MATLAB
• Include all the relevant files when creating the project with mcc.
6-40
7
Intro to MEX-Files
7 Intro to MEX-Files
To create a MEX function, write your program using MATLAB APIs, then build it using the mex
command. The APIs provide these features:
Caution Do not mix functions in the C Matrix API with functions in the MATLAB Data API.
7-2
Choosing MEX Applications
MEX Terms
MEX stands for MATLAB executable and has different meanings, as shown in this table.
See Also
mxArray | matlab::data::Array | mex
More About
• “Tables of MEX Function Source Code Examples” on page 8-14
7-3
7 Intro to MEX-Files
To see the current folders on your path, use the path function. You can add new folders to the path
either by using the addpath function, or by selecting File > SetPath to edit the path.
See Also
path | addpath
7-4
Use Help Files with MEX Functions
For example, copy the following text from the arrayProduct.c MEX source file into a file,
arrayproduct.m.
help arrayproduct
See Also
help
Related Examples
• “Document Build Information in the MEX File” on page 7-57
• “Add Help for Your Program”
7-5
7 Intro to MEX-Files
MATLAB Data
• Its type
• Its dimensions
• The data associated with this array
• If numeric, whether the variable is real or complex
• If sparse, its indices and nonzero maximum elements
• If a structure or an object, the number of fields and field names
To access the mxArray structure, use functions in the C or Fortran Matrix APIs. These functions
allow you to create, read, and query information about the MATLAB data in your MEX files. Matrix
APIs use the mwSize and mwIndex types to avoid portability issues and allow MEX source files to be
compiled correctly on all systems.
Lifecycle of mxArray
Like MATLAB functions, a MEX-file gateway routine on page 8-2 passes MATLAB variables by
reference. However, these arguments are C pointers. A pointer to a variable is the address (location
in memory) of the variable. MATLAB functions handle data storage for you automatically. When
passing data to a MEX-file, you use pointers, which follow specific rules for accessing and
manipulating variables. For information about working with pointers, refer to a programming
reference, such as The C Programming Language by Kernighan, B. W., and D. M. Ritchie.
Note Since variables use memory, you need to understand how your MEX-file creates an mxArray
and your responsibility for releasing (freeing) the memory. This is important to prevent memory leaks.
The lifecycle of an mxArray—and the rules for managing memory—depends on whether it is an input
argument, output argument, or local variable. The function you call to deallocate an mxArray
depends on the function you used to create it. For more information, look up the functions to create
arrays in the C Matrix API.
An mxArray passed to a MEX-file through the prhs input parameter exists outside the scope of the
MEX-file. Do not free memory for any mxArray in the prhs parameter. Also, prhs variables are read-
only; do not modify them in your MEX-file.
If you create an mxArray (allocate memory and create data) for an output argument, the memory and
data exist beyond the scope of the MEX-file. Do not free memory on an mxArray returned in the plhs
output parameter.
7-6
MATLAB Data
Local Variable
You allocate memory whenever you use an mxCreate* function to create an mxArray or when you
call the mxCalloc and associated functions. After observing the rules for handling input and output
arguments, the MEX-file should destroy temporary arrays and free dynamically allocated memory. To
deallocate memory, use either mxDestroyArray or mxFree. For information about which function to
use, see MX Matrix Library.
Data Storage
MATLAB stores data in a column-major (column-wise) numbering scheme, which is how Fortran
stores matrices. MATLAB uses this convention because it was originally written in Fortran. MATLAB
internally stores data elements from the first column first, then data elements from the second
column second, and so on, through the last column.
a =
house
floor
porch
ans =
3 5
If a matrix is N-dimensional, MATLAB represents the data in N-major order. For example, consider a
three-dimensional array having dimensions 4-by-2-by-3. Although you can visualize the data as:
MATLAB internally represents the data for this three-dimensional array in this order:
7-7
7 Intro to MEX-Files
A B C D E F G H I J K L M N O P Q R S T U V W X
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
The mxCalcSingleSubscript function creates the offset from the first element of an array to the
desired element, using N-dimensional subscripting.
The most common data type in MATLAB is the complex double-precision, nonsparse matrix. These
matrices are of type double and have dimensions m-by-n, where m is the number of rows and n is the
number of columns. The data is stored as a vector of interleaved, double-precision numbers where
the real and imaginary parts are stored next to each other. The pointer to this data is referred to as
pa (pointer to array). To test for a noncomplex matrix, call mxIsComplex.
Before MATLAB Version 9.4 (R2018a), MATLAB used a separate storage representation. The data is
stored as two vectors of double-precision numbers—one contains the real data and one contains the
imaginary data. The pointers to this data are referred to as pr (pointer to real data) and pi (pointer
to imaginary data), respectively. A noncomplex matrix is one whose pi is NULL. However, to test for a
noncomplex matrix, call mxIsComplex.
MATLAB supports single-precision floating-point and 8-, 16-, 32-, and 64-bit integers, both signed and
unsigned.
Logical Matrices
The logical data type represents a logical true or false state using the numbers 1 and 0,
respectively. Certain MATLAB functions and operators return logical 1 or logical 0 to indicate
whether a certain condition was found to be true or not. For example, the statement (5 * 10) > 40
returns a logical 1 value.
MATLAB char arrays store data as unsigned 16-bit integers. To convert a MATLAB char array to a C-
style string, call mxArrayToString. To convert a C-style string to a char array, call
mxCreateString.
Cell Arrays
Cell arrays are a collection of MATLAB arrays where each mxArray is referred to as a cell. Cell
arrays allow MATLAB arrays of different types to be stored together. Cell arrays are stored in a
similar manner to numeric matrices, except the data portion contains a single vector of pointers to
mxArrays. Members of this vector are called cells. Each cell can be of any supported data type, even
another cell array.
Structures
A 1-by-1 structure is stored in the same manner as a 1-by-n cell array where n is the number of fields
in the structure. Members of the data vector are called fields. Each field is associated with a name
stored in the mxArray.
7-8
MATLAB Data
Objects
Objects are stored and accessed the same way as structures. In MATLAB, objects are named
structures with registered methods. Outside MATLAB, an object is a structure that contains storage
for an additional class name that identifies the name of the object.
Multidimensional Arrays
MATLAB arrays of any type can be multidimensional. A vector of integers is stored where each
element is the size of the corresponding dimension. The storage method of the data is the same as for
matrices.
Empty Arrays
MATLAB arrays of any type can be empty. An empty mxArray is one with at least one dimension
equal to zero. For example, a double-precision mxArray of type double, where m and n equal 0 and
pa is NULL, is an empty array.
Sparse Matrices
Sparse matrices have a different storage convention from full matrices in MATLAB. The parameter pa
is still an array of double-precision numbers or logical values, but this array contains only nonzero
data elements.
There are three additional parameters: nzmax, ir, and jc. Use the mwSize and mwIndex types when
declaring variables for these parameters.
• nzmax is an integer that contains the length of ir and pa. It is the maximum number of nonzero
elements in the sparse matrix.
• ir points to an integer array of length nzmax containing the row indices of the corresponding
elements in pa.
• jc points to an integer array of length n+1, where n is the number of columns in the sparse
matrix. In C, the first element of an mxArray has an index of 0. The jc array contains column
index information. If the jth column of the sparse matrix has any nonzero elements, jc[j] is the
index into ir and pa of the first nonzero element in the jth column. Index jc[j+1] - 1 contains
the last nonzero element in that column. For the jth column of the sparse matrix, jc[j] is the
total number of nonzero elements in all preceding columns. The last element of the jc array,
jc[n], is equal to nnz, the number of nonzero elements in the entire sparse matrix. If nnz is less
than nzmax, more nonzero entries can be inserted into the array without allocating more storage.
Caution MATLAB does not check the validity of MATLAB data structures created in C/C++ or
Fortran using one of the Matrix Library create functions (for example, mxCreateStructArray).
Using invalid syntax to create a MATLAB data structure can result in unexpected behavior in your
C/C++ or Fortran program.
7-9
7 Intro to MEX-Files
To handle MATLAB arrays, use type mxArray. The following statement declares an mxArray named
myData:
mxArray *myData;
To define the values of myData, use one of the mxCreate* functions. Some useful array creation
routines are mxCreateNumericArray, mxCreateCellArray, and mxCreateCharArray. For
example, the following statement allocates an m-by-1 floating-point mxArray initialized to 0:
C/C++ programmers should note that data in a MATLAB array is in column-major order. (For an
illustration, see “Data Storage” on page 7-7.) Use the MATLAB mxGet* array access routines to read
data from an mxArray.
Manipulating Data
The mxGet* array access routines get references to the data in an mxArray. Use these routines to
modify data in your MEX file. Each function provides access to specific information in the mxArray.
Some useful functions are mxGetDoubles, mxGetComplexDoubles, mxGetM, and mxGetString.
Many of these functions have corresponding mxSet* routines to allow you to modify values in the
array.
The following statements read the input prhs[0] into a C-style string buf.
char *buf;
int buflen;
int status;
buflen = mxGetN(prhs[0])*sizeof(mxChar)+1;
buf = mxMalloc(buflen);
status = mxGetString(prhs[0], buf, buflen);
explore Example
There is an example source MEX file included with MATLAB, called explore.c, that identifies the
data type of an input variable. The source code for this example is in matlabroot/extern/
examples/mex, where matlabroot represents the top-level folder where MATLAB is installed on
your system.
Note In platform-independent discussions that refer to folder paths, this documentation uses the
UNIX® convention. For example, a general reference to the mex folder is matlabroot/extern/
examples/mex.
To build the example MEX file, first copy the file to a writable folder on your path.
copyfile(fullfile(matlabroot,'extern','examples','mex','explore.c'),'.','f')
Type:
7-10
MATLAB Data
x = 2;
explore(x)
------------------------------------------------
Name: prhs[0]
Dimensions: 1x1
Class Name: double
------------------------------------------------
(1,1) = 2
explore accepts any data type. Try using explore with these examples:
explore([1 2 3 4 5])
explore 1 2 3 4 5
explore({1 2 3 4 5})
explore(int8([1 2 3 4 5]))
explore {1 2 3 4 5}
explore(sparse(eye(5)))
explore(struct('name', 'Joe Jones', 'ext', 7332))
explore(1, 2, 3, 4, 5)
explore(complex(3,4))
See Also
More About
• “Data Types”
7-11
7 Intro to MEX-Files
use the following technique to exclude subclasses of built-in types from the input arguments.
• Define a cell array that contains the names of built-in types accepted by your function.
• Call class and strcmp to test for specific types in a MATLAB control statement.
Define a cell array floatTypes that contains the words double and single:
floatTypes = {'double','single'};
ans =
0
7-12
Testing for Most-Derived Class
...
end
7-13
7 Intro to MEX-Files
Verify that you have installed a Supported and Compatible Compilers. For information about
installing a compiler, visit the vendor website.
mex -setup C
copyfile(fullfile(matlabroot,'extern','examples','mex','arrayProduct.c'),'.','f')
This command creates the file arrayProduct.ext, where ext is the value returned by the mexext
function.
Test the function. The arrayProduct function takes a scalar and multiplies it by a 1xN matrix. Call
arrayProduct like a MATLAB function.
s = 5;
A = [1.5, 2, 9];
B = arrayProduct(s,A)
B =
7.5000 10.0000 45.0000
See Also
mex | mexext
More About
• “Change Default Compiler” on page 7-15
• “Build C++ MEX Programs” on page 9-8
External Websites
• Supported and Compatible Compilers
7-14
Change Default Compiler
If you call mex -setup without the lang argument, then MATLAB displays information about the
default C compiler. MATLAB also displays links to the other supported languages. To change the
default for another language, select a link.
If you call mex -setup from an operating system prompt, MATLAB displays the same information.
However, the messages do not contain links. Instead, MATLAB displays the appropriate mex
command syntax for changing the default compiler. Copy the command and paste it into the operating
system prompt.
The compiler you choose remains the default for that language until you call mex -setup to select a
different default.
C Compilers
mex -setup
mex -setup defaults to information about the C compiler. To change the default, select a link to
another compiler.
Alternatively, type:
mex -setup c
C++ Compilers
Fortran Compilers
7-15
7 Intro to MEX-Files
xcode-select -p
See Also
mex
More About
• “Choose a C++ Compiler” on page 8-19
• “Change Default gcc Compiler on Linux System” on page 7-17
External Websites
• Supported and Compatible Compilers
7-16
Change Default gcc Compiler on Linux System
!which gcc
• Change the system $PATH variable. When you change the path, this compiler becomes the default
for all applications on your system.
To change the $PATH variable, add the folder containing the compiler that MATLAB supports to
the beginning of the path. Refer to your operating system documentation for the correct command
to use.
• Select a compiler that MATLAB supports when running the mex command. To change the
compiler, use the varname variable set to GCC, in uppercase letters.
For example, if the currently supported gcc compiler is version 6.3 and it is installed in
the /usr/bin/gcc-6.3 folder on your system, to build timestwo.c, type:
copyfile(fullfile(matlabroot,'extern','examples','refbook','timestwo.c'),'.','f')
mex -v GCC='/usr/bin/gcc-6.3' timestwo.c
Note The mex -setup command does not change the default compiler on Linux.
See Also
More About
• “Change Default Compiler” on page 7-15
External Websites
• Supported and Compatible Compilers
• How can I change my current GCC/G++ version to a supported one?
7-17
7 Intro to MEX-Files
• You want to use an Integrated Development Environment (IDE), rather than the provided script, to
build MEX files.
• You want to exercise more control over the build process than the script uses.
Use the mex -v -n options to display the build commands to configure an IDE. You can also use the
mex script options to modify the build steps.
Include Files
Header files for the MATLAB API (MEX files, engine, and MAT-files). These files are in the
matlabroot\extern\include folder.
• matrix.h — C/C++ header file containing a definition of the mxArray structure and function
prototypes for matrix access routines.
• mex.h — Header file for building C/C++ MEX files. Contains function prototypes for mex routines.
• engine.h — C/C++ header file for MATLAB engine programs. Contains function prototypes for
engine routines.
• mat.h — C/C++ header file for programs accessing MAT-files. Contains function prototypes for
mat routines.
• fintrf.h — Header file for building Fortran MEX files. Contains function prototypes for mex
routines.
See Also
mex
More About
• “Custom Linking to Required API Libraries” on page 1-5
7-18
Call LAPACK and BLAS Functions
• Link your source file to one or both of the libraries, mwlapack and mwblas.
• The mwlapack and mwblas libraries only support 64-bit integers for matrix dimensions. Do
not use the -compatibleArrayDims option.
• To build a MEX file with functions that use complex numbers, see “Pass Separate Complex
Numbers to Fortran Functions” on page 7-23.
4 For information about BLAS or LAPACK functions, see https://www.netlib.org/blas/ or https://
www.netlib.org/lapack/.
copyfile(fullfile(matlabroot,'extern','examples','refbook','matrixMultiply.c'),'.')
The example files are read-only files. To modify an example, ensure that the file is writable by typing:
fileattrib('matrixMultiply.c','+w')
A = [1 3 5; 2 4 7];
B = [-5 8 11; 3 9 21; 4 0 8];
X = matrixMultiply(A,B)
X =
24 35 114
30 52 162
7-19
7 Intro to MEX-Files
about how MATLAB handles arguments to the mexFunction, see “Managing Input and Output
Parameters” on page 8-2.
matrixDivide Example
This example calls the LAPACK function dgesv that modifies its input arguments. The code in this
example makes copies of prhs[0] and prhs[1], and passes the copies to dgesv to preserve the
contents of the input arguments.
To see the example, open matrixDivide.c in the MATLAB Editor. To create the MEX file, copy the
source file to a writable folder.
copyfile(fullfile(matlabroot,'extern','examples','refbook','matrixDivide.c'),'.')
To test, type:
A = [1 2; 3 4];
B = [5; 6];
X = matrixDivide(A,B)
X =
-4.0000
4.5000
When you call a Fortran subroutine, like a function from LAPACK or BLAS, from a C/C++ program, be
sure to pass the arguments by reference. To pass by reference, precede the argument with an
ampersand (&), unless that argument is already a reference. For example, when you create a matrix
using the mxGetDoubles function, you create a reference to the matrix and do not need the
ampersand before the argument.
In the following code snippet, variables m, n, p, one, and zero need the & character to make them a
reference. Variables A, B, C, and chn are pointers, which are references.
7-20
Call LAPACK and BLAS Functions
matrixMultiply Example
The matrixMultiply.c example calls dgemm, passing all arguments by reference. To see the source
code, open matrixMultiply.c in the MATLAB Editor. To build and run this example, see “Build
matrixMultiply MEX Function Using BLAS Functions” on page 7-19.
#include "fintrf.h"
ch1 = 'N'
ch2 = 'N'
one = 1.0
zero = 0.0
A = mxgetpr(prhs(1))
B = mxgetpr(prhs(2))
m = mxgetm(prhs(1))
p = mxgetn(prhs(1))
n = mxgetn(prhs(2))
return
end
7-21
7 Intro to MEX-Files
#if !defined(_WIN32)
#define dgemm dgemm_
#endif
See Also
External Websites
• https://www.netlib.org/lapack/
• https://www.netlib.org/blas/
7-22
Pass Separate Complex Numbers to Fortran Functions
Before MATLAB Version 9.4 (R2018a), MATLAB stored complex numbers differently than Fortran, in
separate, equal length vectors pr and pi. As a result, complex variables exchanged between those
versions of MATLAB and a Fortran function are incompatible. MATLAB provides example conversion
routines mat2fort and fort2mat that change the storage format of complex numbers to address
this incompatibility. The fort.h header file defines the mat2fort and fort2mat functions. The
source code is in the fort.c file.
1 Include the fort.h header file in your source file, using the statement #include "fort.h".
2 Link the fort.c file with your program. Specify the full path, matlabroot/extern/
examples/refbook for fort.c in the build command.
3 To indicate the header file, use the -Ipathname switch. Specify the full path, matlabroot/
extern/examples/refbook for fort.h in the build command.
4 When you specify the full path, replace the term matlabroot with the actual folder name.
5 Build the function using the mex -R2017b option.
1 When allocating storage for the variable, allocate a real variable with twice as much space as you
would for a variable of the same size. Do this because the returned variable uses the Fortran
format, which takes twice the space. See the allocation of zout in the example.
2 To make the variable compatible with MATLAB, use the fort2mat function.
copyfile(fullfile(matlabroot,'extern','examples','refbook','matrixDivideComplex.c'),'.')
Create variables locating the fort.c file and its header file.
7-23
7 Intro to MEX-Files
fortfile = fullfile(matlabroot,'extern','examples','refbook','fort.c');
fortheaderdir = fullfile(matlabroot,'extern','examples','refbook');
Areal = [1 2; 3 4];
Aimag = [1 1; 0 0];
Breal = [5; 6];
Bimag = [0; 0];
Acomplex = complex(Areal,Aimag);
Bcomplex = complex(Breal,Bimag);
X = matrixDivideComplex(Acomplex,Bcomplex)
X =
-4.4000 + 0.8000i
4.8000 - 0.6000i
The calling syntax for a C program calling a Fortran function that returns a value in an output
argument is platform-dependent. On the Windows and Mac platforms, pass the return value as the
first input argument. MATLAB provides a macro, FORTRAN_COMPLEX_FUNCTIONS_RETURN_VOID, to
handle these differences.
The dotProductComplex example computes the dot product X of each element of two complex
vectors A and B. The calling syntax is:
X = dotProductComplex(A,B)
where A and B are complex vectors of the same size and X is a complex scalar.
copyfile(fullfile(matlabroot,'extern','examples','refbook','dotProductComplex.c'),'.')
fortfile = fullfile(matlabroot,'extern','examples','refbook','fort.c');
fortheaderdir = fullfile(matlabroot,'extern','examples','refbook');
mex('-v','-R2017b',['-I' fortheaderdir],'dotProductComplex.c',fortfile,'-lmwblas')
To test, type;
a1 = [1+2i; 2+3i];
b1 = [-1+2i; -1+3i];
X = dotProductComplex(a1,b1)
X =
-16.0000 + 3.0000i
7-24
Pass Separate Complex Numbers to Fortran Functions
copyfile(fullfile(matlabroot,'extern','examples','refbook','utdu_slv.c'),'.')
To build:
fortheaderdir = fullfile(matlabroot,'extern','examples','refbook');
mex('-v','-R2017b',['-I' fortheaderdir],'utdu_slv.c',fortfile,'-lmwlapack')
See Also
7-25
7 Intro to MEX-Files
Since many mathematical libraries use an interleaved complex representation, using the same
representation in your MEX functions eliminates the need to translate data. This simplifies your code
and potentially speeds up the processing when large data sets are involved.
This change does not affect the MATLAB language. You can continue to use the functionality
described in “Complex Numbers” without any modification of your functions and scripts.
• The separate complex API contains the C and Fortran Matrix API functionality in MATLAB R2017b
and earlier.
• The interleaved complex API contains the C Matrix API functionality as of MATLAB R2018a and
the Fortran Matrix API functionality as of MATLAB R2018a Update 3.
To build MEX files with the interleaved complex API, use the mex release-specific build option -
R2018a. To build MEX files with the separate complex API, use the -R2017b build option. The mex
command uses the separate complex API by default. However, in a future version of MATLAB, mex
will use the interleaved complex API (-R2018a option) by default and then you need to modify your
build command. Therefore, to ensure the desired behavior across versions of MATLAB, add the -
R2017b option to your existing build scripts. To write code to support both APIs, see “Add
MX_HAS_INTERLEAVED_COMPLEX to Support Both Complex Number Representations” on page 7-
30.
Note To run a Fortran MEX file built with the interleaved complex API in MATLAB R2018a, you must
use MATLAB R2018a Update 3.
• New typed data access functions. For more information, see “Typed Data Access in C MEX Files”
on page 8-45.
MATLAB mxArray Types C Typed Data Access Fortran Typed Data Access
Functions Functions
mxDOUBLE_CLASS mxGetDoubles mxGetDoubles
mxSetDoubles mxSetDoubles
mxGetComplexDoubles mxGetComplexDoubles
mxSetComplexDoubles mxSetComplexDoubles
7-26
MATLAB Support for Interleaved Complex API in MEX Functions
MATLAB mxArray Types C Typed Data Access Fortran Typed Data Access
Functions Functions
mxSINGLE_CLASS mxGetSingles mxGetSingles
mxSetSingles mxSetSingles
mxGetComplexSingles mxGetComplexSingles
mxSetComplexSingles mxSetComplexSingles
mxINT8_CLASS mxGetInt8s mxGetInt8s
mxSetInt8s mxSetInt8s
mxGetComplexInt8s mxGetComplexInt8s
mxSetComplexInt8s mxSetComplexInt8s
mxUINT8_CLASS mxGetUint8s mxGetUint8s
mxSetUint8s mxSetUint8s
mxGetComplexUint8s mxGetComplexUint8s
mxSetComplexUint8s mxSetComplexUint8s
mxINT16_CLASS mxGetInt16s mxGetInt16s
mxSetInt16s mxSetInt16s
mxGetComplexInt16s mxGetComplexInt16s
mxSetComplexInt16s mxSetComplexInt16s
mxUINT16_CLASS mxGetUint16s mxGetUint16s
mxSetUint16s mxSetUint16s
mxGetComplexUint16s mxGetComplexUint16s
mxSetComplexUint16s mxSetComplexUint16s
mxINT32_CLASS mxGetInt32s mxGetInt32s
mxSetInt32s mxSetInt32s
mxGetComplexInt32s mxGetComplexInt32s
mxSetComplexInt32s mxSetComplexInt32s
mxUINT32_CLASS mxGetUint32s mxGetUint32s
mxSetUint32s mxSetUint32s
mxGetComplexUint32s mxGetComplexUint32s
mxSetComplexUint32s mxSetComplexUint32s
mxINT64_CLASS mxGetInt64s mxGetInt64s
mxSetInt64s mxSetInt64s
mxGetComplexInt64s mxGetComplexInt64s
mxSetComplexInt64s mxSetComplexInt64s
mxUINT64_CLASS mxGetUint64s mxGetUint64s
mxSetUint64s mxSetUint64s
mxGetComplexUint64s mxGetComplexUint64s
mxSetComplexUint64s mxSetComplexUint64s
• Matrix API functions added to the -R2018a API:
7-27
7 Intro to MEX-Files
• mxCopyComplex16ToPtr (Fortran)
• mxCopyPtrToComplex16 (Fortran)
• mxCopyComplex8ToPtr (Fortran)
• mxCopyPtrToComplex8 (Fortran)
The mex command uses the -R2017b API by default. However, in a future version of MATLAB, mex
will use the interleaved complex API -R2018a by default and then you need to modify your build
command. Therefore, to ensure the desired behavior across versions of MATLAB, add the
compatibility flag -R2017b to your build scripts.
See Also
More About
• “Upgrade MEX Files to Use Interleaved Complex API” on page 7-29
• C Matrix API
• “Fortran Matrix API”
7-28
Upgrade MEX Files to Use Interleaved Complex API
Note If you build your MEX files using the mex command with the -compatibleArrayDims option,
then you first must update the source code to use the 64-bit API. For information, see “Upgrade MEX
Files to Use 64-Bit API” on page 7-40.
1 Review your code for usage of pr and pi pointers, the pointers returned by the mxGetPr/
mxGetPi and mxGetData/mxGetImagData functions. In the interleaved complex API, there is
one pointer, pa, the value returned by mxGetDoubles and the other typed data functions. It is
important to check an input array for complexity before attempting to read the data. Calls to
mxGetPr and mxGetData on complex arrays return different results in the interleaved complex
API than in the separate complex API.
2 Prepare your code before editing.
Before modifying your code, verify that the MEX function works with the -R2017b API. At a
minimum, build a list of expected inputs and outputs, or create a full test suite. Use these tests to
compare the results with the updated source code. The results should be identical.
Compare the results of running your MEX function compiled with the interleaved complex API
with the results from your original binary. If there are any differences or failures, use a debugger
7-29
7 Intro to MEX-Files
to investigate the cause. For information on the capabilities of your debugger, refer to your
compiler documentation.
7 “Add Build Information to MEX Help File” on page 7-35
7-30
Upgrade MEX Files to Use Interleaved Complex API
7-31
7 Intro to MEX-Files
Complex C mxArrays
Suppose that you have the following complex mxArray variables and want to add the real numbers
and the imaginary numbers of x and y to create array z. Arrays x and y are the same size.
mxArray * x, y, z;
Instead of creating two pointers xr and xi for array x, create one pointer xc of type
mxComplexDouble. To access the real and imaginary parts of element xc[i], use xc[i].real and
xc[i].imag.
...
/* perform addition on element i */
zr[i] = xr[i] + yr[i];
zi[i] = xi[i] + yi[i];
The following code copies an mxArray into an output argument. The code shows how to test for and
copy complex arrays.
7-32
Upgrade MEX Files to Use Interleaved Complex API
Suppose that you have two complex double mxArrays and want to pass them to a Fortran function
with input arguments x and y defined as follows.
Instead of separately converting the real and imaginary parts of each mxArray, use the
mxGetComplexDoubles function.
The following code shows how to use mxMakeArrayComplex to convert a real, double, input array to
an interleaved complex mxArray. For more examples, see mxMakeArrayComplex (C).
if (mxMakeArrayComplex(plhs[0])) {
mxDouble *dc = (mxDouble*)mxMalloc(rows*cols*sz);
mxComplexDouble *dt = mxGetComplexDoubles(plhs[0]);
for (int i = 0 ; i < rows*cols ; i++)
mxSetImagData(plhs[0], dc); {
for (int i = 0 ; i < rows*cols ; i++) dt[i].imag = i+1;
{ }
}
dc[i] = i+1;
}
7-33
7 Intro to MEX-Files
• mxGetPi
• mxSetPi
• mxGetImagData
• mxSetImagData
You can replace calls to mxGetPr and mxGetPi with a call to mxGetComplexDoubles. This function
verifies that your array contains elements of type mxComplexDouble. Likewise,
mxSetComplexDoubles replaces mxSetPr and mxSetPi.
The mxGetData and mxGetImagData functions do not check the type of the array. Instead, you must
cast the return value to the pointer type that matches the type specified by the input. Replace calls to
mxGetData and mxGetImagData with the single, appropriate, typed data access function, for
example, mxGetComplexInt64s.
• mxGetPr
• mxSetPr
• mxGetData (C) and mxGetData (Fortran) - for numeric arrays
• mxSetData (C) and mxSetData (Fortran) - for numeric arrays
You can replace calls to mxGetPr with a call to mxGetDoubles. This function verifies that your array
contains elements of type mxDouble. Likewise, mxSetDoubles replaces mxSetPr. To replace calls to
mxGetData and mxSetData functions, choose the appropriate typed data access function, for
example, mxGetInt64s and mxSetInt64s.
7-34
Upgrade MEX Files to Use Interleaved Complex API
help displayTypesafeNumeric
displayTypesafeNumeric.m Help file for displayTypesafeNumeric C MEX function
See Also
mex
More About
• “Troubleshooting MEX API Incompatibilities” on page 7-38
• “Do I Need to Upgrade My MEX Files to Use Interleaved Complex API?” on page 7-36
7-35
7 Intro to MEX-Files
7-36
Do I Need to Upgrade My MEX Files to Use Interleaved Complex API?
See Also
More About
• “MATLAB Support for Interleaved Complex API in MEX Functions” on page 7-26
• “Upgrade MEX Files to Use Interleaved Complex API” on page 7-29
• “Troubleshooting MEX API Incompatibilities” on page 7-38
7-37
7 Intro to MEX-Files
This error occurs when you compile two or more files independently with the -c compile-only option,
then try to build them into a MEX function. For example:
MEX File Compiled With One API And Linked With Another
This error occurs when you compile a file with the -c compile-only option and then link with a version
of the API that is incompatible. For example, if you use the following commands to build a MEX file,
then the function errors at runtime.
C++ MEX File Using MATLAB Data API Compiled With Incompatible
Option
If you create a C++ MEX file using functions in the “MATLAB Data API”, then the following build
command errors.
mex function.cpp
7-38
Troubleshooting MEX API Incompatibilities
See Also
More About
• “Upgrade MEX Files to Use Interleaved Complex API” on page 7-29
• “Do I Need to Upgrade My MEX Files to Use Interleaved Complex API?” on page 7-36
7-39
7 Intro to MEX-Files
You can continue to use the 32-bit API by calling the mex command with the -
compatibleArrayDims option. However, for more information about using this option, see “What If
I Do Not Upgrade?” on page 7-46.
To review and update MEX file source code, use the following checklist.
1 Prepare your code before editing — see “Back Up Files and Create Tests” on page 7-40.
2 Iteratively change and test code.
Before building your MEX files with the 64-bit API, refactor your existing code using “Update
Variables” on page 7-40 and, for Fortran, “Upgrade Fortran MEX Files to use 64-bit API” on
page 7-48.
• Build with the 32-bit API. For example, to build myMexFile.c, type:
mex myMexFile.c
4 Resolve failures and warnings — see “Resolve -largeArrayDims Build Failures and Warnings” on
page 7-43.
5 Compare Results — see “Execute 64-Bit MEX File and Compare Results with 32-Bit Version” on