0% found this document useful (0 votes)
411 views1,008 pages

Matlab External

Uploaded by

Leonel Lizama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
411 views1,008 pages

Matlab External

Uploaded by

Leonel Lizama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1008

MATLAB®

External Interfaces

R2021b
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


1 Apple Hill Drive
Natick, MA 01760-2098
MATLAB® External Interfaces
© COPYRIGHT 1984–2021 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied
only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form
without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through
the federal government of the United States. By accepting delivery of the Program or Documentation, the government
hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer
software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014.
Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain
to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government) and shall
supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is
inconsistent in any respect with federal procurement law, the government agrees to return the Program and
Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be
trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for
more information.
Revision History
December 1996 First printing New for MATLAB 5 (release 8)
July 1997 Online only Revised for MATLAB 5.1 (Release 9)
January 1998 Second printing Revised for MATLAB 5.2 (Release 10)
October 1998 Third printing Revised for MATLAB 5.3 (Release 11)
November 2000 Fourth printing Revised and renamed for MATLAB 6.0 (Release 12)
June 2001 Online only Revised for MATLAB 6.1 (Release 12.1)
July 2002 Online only Revised for MATLAB 6.5 (Release 13)
January 2003 Online only Revised for MATLAB 6.5.1 (Release 13SP1)
June 2004 Online only Revised for MATLAB 7.0 (Release 14)
October 2004 Online only Revised for MATLAB 7.0.1 (Release 14SP1)
September 2005 Online only Revised for MATLAB 7.1 (Release 14SP3)
March 2006 Online only Revised for MATLAB 7.2 (Release 2006a)
September 2006 Online only Revised for MATLAB 7.3 (Release 2006b)
March 2007 Online only Revised for MATLAB 7.4 (Release 2007a)
September 2007 Online only Revised for MATLAB 7.5 (Release 2007b)
March 2008 Online only Revised for MATLAB 7.6 (Release 2008a)
October 2008 Online only Revised for MATLAB 7.7 (Release 2008b)
March 2009 Online only Revised for MATLAB 7.8 (Release 2009a)
September 2009 Online only Revised for MATLAB 7.9 (Release 2009b)
March 2010 Online only Revised for MATLAB 7.10 (Release 2010a)
September 2010 Online only Revised for MATLAB 7.11 (Release 2010b)
April 2011 Online only Revised for MATLAB 7.12 (Release 2011a)
September 2011 Online only Revised for MATLAB 7.13 (Release 2011b)
March 2012 Online only Revised for MATLAB 7.14 (Release 2012a)
September 2012 Online only Revised for MATLAB 8.0 (Release 2012b)
March 2013 Online only Revised for MATLAB 8.1 (Release 2013a)
September 2013 Online only Revised for MATLAB 8.2 (Release 2013b)
March 2014 Online only Revised for MATLAB 8.3 (Release 2014a)
October 2014 Online only Revised for MATLAB 8.4 (Release 2014b)
March 2015 Online only Revised for MATLAB 8.5 (Release 2015a)
September 2015 Online only Revised for MATLAB 8.6 (Release 2015b)
March 2016 Online only Revised for MATLAB 9.0 (Release 2016a)
September 2016 Online only Revised for MATLAB 9.1 (Release 2016b)
March 2017 Online only Revised for MATLAB 9.2 (Release 2017a)
September 2017 Online only Revised for MATLAB 9.3 (Release 2017b)
March 2018 Online only Revised for MATLAB 9.4 (Release 2018a)
September 2018 Online only Revised for MATLAB 9.5 (Release 2018b)
March 2019 Online only Revised for MATLAB 9.6 (Release 2019a)
September 2019 Online only Revised for MATLAB 9.7 (Release 2019b)
March 2020 Online only Revised for MATLAB 9.8 (Release 2020a)
September 2020 Online only Revised for MATLAB 9.9 (Release 2020b)
March 2021 Online only Revised for MATLAB 9.10 (Release 2021a)
September 2021 Online only Revised for MATLAB 9.11 (Release 2021b)
Contents

External Programming Languages and Systems


1
Integrate MATLAB with External Programming Languages and Systems
.......................................................... 1-2
Call C/C++ Code from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Use Objects from Other Programming Languages in MATLAB . . . . . . . . . . 1-3
Call MATLAB from Another Programming Language . . . . . . . . . . . . . . . . . 1-3
Call Your Functions as MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Communicate with Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

Custom Linking to Required API Libraries . . . . . . . . . . . . . . . . . . . . . . . . . 1-5


C++ MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
C++ Engine Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
C MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
C Engine Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
C MAT-File Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7

External Data Interface (EDI)


2
Create Arrays with C++ MATLAB Data API . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Create Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Operate on Each Element in an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3

Copy C++ MATLAB Data Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4


Avoid Unnecessary Data Copying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4

C++ Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5

Access C++ Data Array Container Elements . . . . . . . . . . . . . . . . . . . . . . . . 2-6


Modify By Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Copy Data from Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6

Operate on C++ Arrays Using Visitor Pattern . . . . . . . . . . . . . . . . . . . . . . . 2-8


Dispatch on Array or Array Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Overloading operator() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Visitor Class to Display Contents of Cell Array . . . . . . . . . . . . . . . . . . . . . 2-9
Visitor Class to Modify Contents of Cell Array . . . . . . . . . . . . . . . . . . . . . 2-10

MATLAB Data API Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12


matlab::data::CanOnlyUseOneStringIndexException . . . . . . . . . . . . . . . . 2-12
matlab::data::CantAssignArrayToThisArrayException . . . . . . . . . . . . . . . 2-12
matlab::data::CantIndexIntoEmptyArrayException . . . . . . . . . . . . . . . . . 2-13

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

MATLAB Data API Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16


matlab::data::ArrayDimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
matlab::data::Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
matlab::data::MATLABString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
matlab::data::ObjectArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
matlab::data::String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
matlab::data::Struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
buffer_ptr_t and buffer_deleter_t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
iterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
const_iterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
const_reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17

Using Java Libraries from MATLAB


3
Getting Started with Java Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Platform Support for JVM Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Learn More About Java Programming Language . . . . . . . . . . . . . . . . . . . . 3-2

Call Java Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3


Choose Class Constructor to Create Java Object . . . . . . . . . . . . . . . . . . . . 3-3
Shorten Class Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Create Array List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Pass MATLAB Data to add Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Add Elements to ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3

vi Contents
Java Objects Are References in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Use ArrayList Object in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4

Simplify Java Class Names Using import Function . . . . . . . . . . . . . . . . . . . 3-6

Java Class Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7

Static Path of Java Class Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9


Create javaclasspath.txt File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9
Add Individual (Unpackaged) Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10
Add Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10
Add JAR File Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10

Load Java Class Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12

Locate Native Method Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13

Load Class Using Java Class.forName Method . . . . . . . . . . . . . . . . . . . . . 3-14

Dynamic Path of Java Class Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-15

Call Method in Your Own Java Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-16

How MATLAB Represents Java Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-17


Array Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-17
Shape of Java Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-17
Interpret Size of Java Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-17
Interpret Number of Dimensions of Java Arrays . . . . . . . . . . . . . . . . . . . 3-18
Display Java Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-18

Create Array of Java Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19


Create Array of Primitive Java Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19

Access Elements of Java Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-21


MATLAB Array Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-21
Single Subscript Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-21
Colon Operator Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22
Using END in a Subscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23
Converting Object Array Elements to MATLAB Types . . . . . . . . . . . . . . . 3-23

Assign Values to Java Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25


Single Subscript Indexing Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25
Linear Array Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-26
Empty Matrix Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-26
Subscripted Deletion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-26

Concatenate Java Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28


Two-Dimensional Horizontal Concatenation . . . . . . . . . . . . . . . . . . . . . . 3-28
Vector Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28

Create Java Array References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-31

Create Copy of Java Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-32

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

Save and Load Java Objects to MAT-Files . . . . . . . . . . . . . . . . . . . . . . . . . 3-36

Data Fields of Java Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37


Access Public and Private Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37
Display Public Data Fields of Java Object . . . . . . . . . . . . . . . . . . . . . . . . 3-37
Access Static Field Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38

Determine Class of Java Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-39

Method Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-40


Display Method Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-40
Display Method Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-40
Display Syntax in Figure Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-40

Determine What Classes Define a Method . . . . . . . . . . . . . . . . . . . . . . . . 3-42

Java Methods That Affect MATLAB Commands . . . . . . . . . . . . . . . . . . . . 3-43


Changing the Effect of disp and display . . . . . . . . . . . . . . . . . . . . . . . . . 3-43
Changing the Effect of isequal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-43
Changing the Effect of double, string, and char . . . . . . . . . . . . . . . . . . . 3-43

How MATLAB Handles Undefined Methods . . . . . . . . . . . . . . . . . . . . . . . 3-44

Avoid Calling Java main Methods in MATLAB . . . . . . . . . . . . . . . . . . . . . . 3-45

Pass Data to Java Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-46


MATLAB Type to Java Type Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-46
How Array Dimensions Affect Conversion . . . . . . . . . . . . . . . . . . . . . . . . 3-47
Convert Numbers to Integer Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 3-47
Pass String Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-48
Pass Java Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-48
Pass Empty Matrices, Nulls, and Missing Values . . . . . . . . . . . . . . . . . . . 3-49
Overloaded Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-49

Handle Data Returned from Java Methods . . . . . . . . . . . . . . . . . . . . . . . . 3-51


Primitive Return Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
java.lang.Object Return Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
Functions to Convert Java Objects to MATLAB Types . . . . . . . . . . . . . . . 3-52

Java Heap Memory Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-56

Java Methods With Optional Input Arguments . . . . . . . . . . . . . . . . . . . . . 3-57

Call Back into MATLAB from Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-58

Java Packages to Be Removed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-59

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

Custom Applications to Access MAT-Files . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3


Why Write Custom Applications? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
MAT-File Interface Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Exchanging Data Files Between Platforms . . . . . . . . . . . . . . . . . . . . . . . . 4-4

MAT-File API Library and Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5


MAT-File API Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
MAT-File API Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Example Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6

What You Need to Build Custom Applications . . . . . . . . . . . . . . . . . . . . . . 4-7

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

Create MAT-File in C or C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12


Create MAT-File in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12
Create MAT-File in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12

Read MAT-File in C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13

Create MAT-File in Fortran . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14

Read MAT-File in Fortran . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15

Work with mxArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-16


Read Structures from a MAT-File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-16
Read Cell Arrays from a MAT-File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17

Table of MAT-File Source Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18

Build on macOS and Linux Operating Systems . . . . . . . . . . . . . . . . . . . . . 4-19


Set Run-Time Library Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-19
Build Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20

Build on Windows Operating Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-21

Share MAT-File Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-22

ix
Calling Functions in C++ Shared Libraries from MATLAB
5
What Types of Files Define Your Library? . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3

Requirements for Building Interface to C++ Libraries . . . . . . . . . . . . . . . 5-4


Cpp Source and Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Shared Library Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Compiler Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4

Set Run-Time Library Path for C++ Interface . . . . . . . . . . . . . . . . . . . . . . . 5-6


Temporarily Set Run-Time Library Path in MATLAB on Windows . . . . . . . . 5-6
Temporarily Set Run-Time Library Path at System Prompt . . . . . . . . . . . . 5-6

Steps to Publish a MATLAB Interface to a C++ Library . . . . . . . . . . . . . . . 5-8

Header File and Import Library File on Windows . . . . . . . . . . . . . . . . . . . 5-10

Header and CPP Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11

Header File and Dynamic Shared Library File on macOS . . . . . . . . . . . . 5-12

Call Functions in Windows Interface to C++ Shared Library . . . . . . . . . 5-13


Set Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13
View Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13
Call Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14

Call Functions in Linux Interface to C++ Shared Library . . . . . . . . . . . . 5-15


Set Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15
View Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15
Call Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16

Header-Only HPP File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17

Display Help for MATLAB Interface to C++ Library . . . . . . . . . . . . . . . . . 5-18

Publish Help Text for MATLAB Interface to C++ Library . . . . . . . . . . . . 5-20


Automatically Use C++ Comments for Help Text . . . . . . . . . . . . . . . . . . 5-20
Manually Update Help Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21
Compare Generated Help With Header File Comments . . . . . . . . . . . . . . 5-22

Define MATLAB Interface for C++ Library . . . . . . . . . . . . . . . . . . . . . . . . 5-24


How to Complete Definitions in Library Definition File . . . . . . . . . . . . . . 5-24
Autodefine Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-25
Reconcile MATLAB Signature Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . 5-25
Customize Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-25
Customize Function Template Names . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-25
Dimension Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-26

Define Missing SHAPE Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-28


Define Pointer Argument to Fixed Scalar . . . . . . . . . . . . . . . . . . . . . . . . 5-28
Define Pointer Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-28
Define Array Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-29
Define Output Pointer Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-29

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

Define Missing MLTYPE Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-35

Define Missing DIRECTION Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-36

Build C++ Library Interface and Review Contents . . . . . . . . . . . . . . . . . . 5-37


Build From Library Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-37
One-Step Build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-37
Review Contents of Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-37

Sample C++ Library Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-38

Call Functions in C++ Shared Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-39


Set Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-39
Display Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-39
Call Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-39

Limitations to C/C++ Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-40


Data Types Not Supported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-40
Language Features Not Supported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-41
Inheriting C++ class in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-41
Unsupported Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-41

C++ Names That Are Invalid in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 5-43


Rename Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-43
Use Invalid Property Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-43
Use Invalid Enumerated Value Names . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-43
Certain Class Names with typedef Aliases Not Supported . . . . . . . . . . . . 5-44

Troubleshooting C++ Library Definition Issues . . . . . . . . . . . . . . . . . . . . 5-45


MATLAB Did Not Create MLX Definition File . . . . . . . . . . . . . . . . . . . . . 5-45
Cannot Open or Too Slow to Load MLX Definition File . . . . . . . . . . . . . . 5-45
Shape Value Not Found . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-45
Invalid Shape Value Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-45
Why Is a Function or a Type Missing from the Definition File? . . . . . . . . 5-45
Generated Library Definition MLX File . . . . . . . . . . . . . . . . . . . . . . . . . . 5-45
Build Error undefined reference or unresolved external symbol . . . . . . . 5-46

Troubleshooting MATLAB Interface to C++ Library Issues . . . . . . . . . . . 5-47


Library Interface Does Not Exist Or Is Not Loaded . . . . . . . . . . . . . . . . . 5-47
Library Interface Does Not Contain Any Instances Of Type . . . . . . . . . . . 5-47
Invalid clib Array Element Type Name . . . . . . . . . . . . . . . . . . . . . . . . . . 5-47
First Letter Of Type Must Be Capitalized . . . . . . . . . . . . . . . . . . . . . . . . 5-47
Access Violation When Calling Library Function . . . . . . . . . . . . . . . . . . . 5-48

C++ to MATLAB Data Type Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-49


Numeric Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-49
String and Character Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-51
bool Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-54
Static Data Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-54

xi
User-Defined Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-55
nullptr Argument Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-57
void* Argument Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-57
Unsupported Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-59

MATLAB Object For C++ Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-61


Create MATLAB Array of C++ Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 5-61
Convert MATLAB Array to C++ Array Object . . . . . . . . . . . . . . . . . . . . . 5-62
MATLAB C++ Object Array Properties . . . . . . . . . . . . . . . . . . . . . . . . . . 5-62
MATLAB C++ Object Array Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-62
Treat C++ Native Arrays of Fundamental Type as MATLAB Fundamental
Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-63
Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-63

Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-64

Errors Parsing Header Files on macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-65

Build Error Due to Compile-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . . 5-66

Lifetime Management of C++ Objects in MATLAB . . . . . . . . . . . . . . . . . . 5-67


Pass Ownership of Memory to the Library . . . . . . . . . . . . . . . . . . . . . . . . 5-67
Pass Ownership of Memory to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 5-67

Modify Library Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-69


Set Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-69
Define MATLAB Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-69
Update Generated Help Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-70
Build Library and Display Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-70

C++ Limitation Workaround Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-72


Class Objects in std Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-72
Class Templates With Incomplete or Missing Instantiations . . . . . . . . . . . 5-75
Preprocessor Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-76
String Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-77
Build Example Shared Library Files on Windows . . . . . . . . . . . . . . . . . . . 5-79

Use C++ Objects and Functions in parfor Loops . . . . . . . . . . . . . . . . . . . 5-80

Initialize Pointer Members of C++ Structures for MATLAB Interface to


Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-81

C++ Language Opaque Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-82

Define void* and void** Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-83


void* Return Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-83
void* Input Argument Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-84
void** Input Argument Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-85
MATLABType as Object of Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-87
Memory Management for void* and void** Arguments . . . . . . . . . . . . . . 5-88

Use Function Type Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-89


Function Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-89
Call C++ Functions With Function Type Input . . . . . . . . . . . . . . . . . . . . 5-89

xii Contents
Use Function and Member Function Templates . . . . . . . . . . . . . . . . . . . . 5-91
Overloaded Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-91
Unique Function Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-91

Generate Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-93


Verify Selected C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-93
Generate Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-93
Open Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-93

Generate Interface on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-94


Verify Selected C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-94
Generate Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-94
Open Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-94

Header File and Shared Object File on Linux . . . . . . . . . . . . . . . . . . . . . . 5-95

Generate Interface on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-96


Verify Selected C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-96
Generate Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-96
Open Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-96

Generate Interface on macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-97


Verify Selected C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-97
Generate Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-97
Open Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-97

Define Missing Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-98

Define Missing Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-100

Define Missing Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-102

Define Missing Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-104

Build Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-106


Validate Edits to Library Definition File . . . . . . . . . . . . . . . . . . . . . . . . 5-106
View Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-106
Build Interface and Add to MATLAB Path . . . . . . . . . . . . . . . . . . . . . . . 5-106

Build Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-108


Validate Edits to Library Definition File . . . . . . . . . . . . . . . . . . . . . . . . 5-108
View Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-108
Build Interface and Add to MATLAB Path . . . . . . . . . . . . . . . . . . . . . . . 5-108

Build Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-110


Validate Edits to Library Definition File . . . . . . . . . . . . . . . . . . . . . . . . 5-110
View Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-110
Build Interface and Add to MATLAB Path . . . . . . . . . . . . . . . . . . . . . . . 5-110

Build Interface to matrixoperations Library . . . . . . . . . . . . . . . . . . . . . . 5-112


Validate Edits to Library Definition File . . . . . . . . . . . . . . . . . . . . . . . . 5-112
View Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-112
Build Interface and Add to MATLAB Path . . . . . . . . . . . . . . . . . . . . . . . 5-112

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

Call Library Functions on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-116


Set System Path to Library File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-116
Set MATLAB Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-116
View Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-116
Call Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-116

Call Library Functions on macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-118


Set System Path to Library File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-118
Set MATLAB Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-118
View Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-118
Call Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-118

Call matrixoperations Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . 5-120


Set MATLAB Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-120
View Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-120
Call Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-120

Generate Interface to school Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-121


Verify Selected C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-121
Generate Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-121
Open Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-121

Define Missing Constructs in Interface to school Library . . . . . . . . . . . 5-122

Build Interface to school Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-123


Validate Edits to Library Definition File . . . . . . . . . . . . . . . . . . . . . . . . 5-123
View Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-123
Build Interface and Add to MATLAB Path . . . . . . . . . . . . . . . . . . . . . . . 5-124

Call school Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-125


View Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-125
Call Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-125
Distribute Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-125

Calling Functions in C Shared Libraries from MATLAB


6
Call C Functions in Shared Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2

Invoke Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3

View Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4

Load and Unload Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5

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

Limitations Using Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9


MATLAB Returns Pointers to Structures . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9
Structure Cannot Contain Pointers to Other Structures . . . . . . . . . . . . . . . 6-9
Requirements for MATLAB Structure Arguments . . . . . . . . . . . . . . . . . . . 6-9
Requirements for C struct Field Names . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9

Loading Library Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10

No Matching Signature Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11

MATLAB Terminates Unexpectedly When Calling Function in Shared


Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-12

Pass Arguments to Shared C Library Functions . . . . . . . . . . . . . . . . . . . . 6-13


C and MATLAB Equivalent Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13
How MATLAB Displays Function Signatures . . . . . . . . . . . . . . . . . . . . . . 6-14
NULL Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15
Manually Convert Data Passed to Functions . . . . . . . . . . . . . . . . . . . . . . 6-15

Shared Library shrlibsample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-17

Pass String Arguments Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-18


stringToUpper Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-18
Convert MATLAB Character Array to Uppercase . . . . . . . . . . . . . . . . . . . 6-18

Pass Structures Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-20


addStructFields and addStructByRef Functions . . . . . . . . . . . . . . . . . . . 6-20
Add Values of Fields in Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-21
Preconvert MATLAB Structure Before Adding Values . . . . . . . . . . . . . . . 6-21
Autoconvert Structure Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-22
Pass Pointer to Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-22

Pass Enumerated Types Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-24


readEnum Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-24
Display Enumeration Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-24

Pass Pointers Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-26


multDoubleRef Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-26
Pass Pointer of Type double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-26
Create Pointer Offset from Existing lib.pointer Object . . . . . . . . . . . . . . . 6-27
Multilevel Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-27
allocateStruct and deallocateStruct Functions . . . . . . . . . . . . . . . . . . . . 6-27
Pass Multilevel Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-28
Return Array of Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-28

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

Iterate Through lib.pointer Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-33


Create Cell Array from lib.pointer Object . . . . . . . . . . . . . . . . . . . . . . . . 6-33
Perform Pointer Arithmetic on Structure Array . . . . . . . . . . . . . . . . . . . . 6-34

Represent Pointer Arguments in C Shared Library Functions . . . . . . . . . 6-35


Pointer Arguments in C Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-35
Put String into Void Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-35
Memory Allocation for External Library . . . . . . . . . . . . . . . . . . . . . . . . . 6-36

Represent Structure Arguments in C Shared Library Functions . . . . . . . 6-37


Structure Argument Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-37
Find Structure Field Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-37
Strategies for Passing Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-37

Explore libstruct Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-38

MATLAB Prototype Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-39


When to Use Prototype Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-39
How to Create Prototype Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-39
How to Specify Thunk Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-39
Deploy Applications That Use loadlibrary . . . . . . . . . . . . . . . . . . . . . . . . 6-39
loadlibrary in Parallel Computing Environment . . . . . . . . . . . . . . . . . . . . 6-40
Change Function Signature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-40
Rename Library Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-40
Load Subset of Functions in Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-40
Call Function with Variable Number of Arguments . . . . . . . . . . . . . . . . . 6-40

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

MEX File Placement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4


MEX Files on Windows Network Drives . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4

Use Help Files with MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5

MATLAB Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6


The MATLAB Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6
Lifecycle of mxArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6
Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
MATLAB Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8

xvi Contents
Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
Using Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9

Testing for Most-Derived Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12


Testing for a Category of Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12
Another Test for Built-In Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12

Build C MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14

Change Default Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15


To Change Default on Windows Systems . . . . . . . . . . . . . . . . . . . . . . . . . 7-15
To Change Default on Linux Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15
To Change Default on macOS Systems . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16
Do Not Use mex -f optionsfile Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16

Change Default gcc Compiler on Linux System . . . . . . . . . . . . . . . . . . . . 7-17

Custom Build with MEX Script Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18


Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18

Call LAPACK and BLAS Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-19


Build matrixMultiply MEX Function Using BLAS Functions . . . . . . . . . . . 7-19
Preserve Input Values from Modification . . . . . . . . . . . . . . . . . . . . . . . . . 7-19
Pass Arguments to Fortran Functions from C/C++ Programs . . . . . . . . . 7-20
Pass Arguments to Fortran Functions from Fortran Programs . . . . . . . . . 7-21
Modify Function Name on UNIX Systems . . . . . . . . . . . . . . . . . . . . . . . . 7-22

Pass Separate Complex Numbers to Fortran Functions . . . . . . . . . . . . . . 7-23


Handling Complex Number Input Values . . . . . . . . . . . . . . . . . . . . . . . . . 7-23
Handling Complex Number Output Arguments . . . . . . . . . . . . . . . . . . . . 7-23
Pass Complex Variables — matrixDivideComplex . . . . . . . . . . . . . . . . . . . 7-23
Handle Fortran Complex Return Type — dotProductComplex . . . . . . . . . 7-24
Symmetric Indefinite Factorization Using LAPACK — utdu_slv . . . . . . . . 7-25

MATLAB Support for Interleaved Complex API in MEX Functions . . . . . 7-26


Separate Complex API and Interleaved Complex API . . . . . . . . . . . . . . . 7-26
Matrix API Changes Supporting Interleaved Complex . . . . . . . . . . . . . . . 7-26
Writing MEX Functions with Interleaved Complex API . . . . . . . . . . . . . . 7-28
MEX Functions Created in MATLAB R2017b and Earlier . . . . . . . . . . . . . 7-28

Upgrade MEX Files to Use Interleaved Complex API . . . . . . . . . . . . . . . . 7-29


Check Array Complexity Using mxIsComplex . . . . . . . . . . . . . . . . . . . . . 7-30
Add MX_HAS_INTERLEAVED_COMPLEX to Support Both Complex Number
Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-30
Use Typed Data Access Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-31
Handle Complex mxArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-32
Maintain Complexity of mxArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33
Replace Separate Complex Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-34
Calculate Array Data Size with mxGetElementSize . . . . . . . . . . . . . . . . . 7-34
Consider Replacing To-Be-Phased-Out Functions . . . . . . . . . . . . . . . . . . 7-34
Add Build Information to MEX Help File . . . . . . . . . . . . . . . . . . . . . . . . . 7-35

Do I Need to Upgrade My MEX Files to Use Interleaved Complex API?


......................................................... 7-36
Can I Run Existing MEX Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-36

xvii
Must I Update My Source MEX Files? . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-36

Troubleshooting MEX API Incompatibilities . . . . . . . . . . . . . . . . . . . . . . . 7-38


File Is Not A MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-38
MEX File Compiled With Incompatible Options . . . . . . . . . . . . . . . . . . . . 7-38
MEX File Compiled With One API And Linked With Another . . . . . . . . . . 7-38
C++ MEX File Using MATLAB Data API Compiled With Incompatible Option
..................................................... 7-38
Custom-built MEX File Not Supported In Current Release . . . . . . . . . . . 7-38
MEX File Is Compiled With Outdated Option . . . . . . . . . . . . . . . . . . . . . . 7-38
MEX File Calls An Untyped Data Access Function . . . . . . . . . . . . . . . . . . 7-39
MEX File Calls A 32-bit Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-39
MEX File Does Not Contain An Entry Point . . . . . . . . . . . . . . . . . . . . . . . 7-39
MEX File Built In MATLAB Release Not Supported In Current Release . . 7-39

Upgrade MEX Files to Use 64-Bit API . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-40


Back Up Files and Create Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-40
Update Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-40
Update Arguments Used to Call Functions in the 64-Bit API . . . . . . . . . . 7-41
Update Variables Used for Array Indices and Sizes . . . . . . . . . . . . . . . . . 7-41
Analyze Other Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-42
Test, Debug, and Resolve Differences After Each Refactoring Iteration . . 7-43
Resolve -largeArrayDims Build Failures and Warnings . . . . . . . . . . . . . . 7-43
Execute 64-Bit MEX File and Compare Results with 32-Bit Version . . . . . 7-43
Experiment with Large Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-43

MATLAB Support for 64-Bit Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-45

What If I Do Not Upgrade? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-46


Can I Run Existing Binary MEX Files? . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-46
Must I Update Source MEX Files on 64-Bit Platforms? . . . . . . . . . . . . . . 7-46

Upgrade Fortran MEX Files to use 64-bit API . . . . . . . . . . . . . . . . . . . . . . 7-48


Use Fortran API Header File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-48
Declare Fortran Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-48
Require Fortran Type Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-48
Use Variables in Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-48
Manage Reduced Fortran Compiler Warnings . . . . . . . . . . . . . . . . . . . . . 7-49

Upgrade MEX Files to Use Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . 7-50


Replace mexGet and mexSet Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 7-50
mex Automatically Converts Handle Type . . . . . . . . . . . . . . . . . . . . . . . . 7-52
I Want to Rebuild MEX Source Code Files . . . . . . . . . . . . . . . . . . . . . . . . 7-52
I Do Not Have MEX Source Code File . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-52

MEX Platform Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-54

Invalid MEX File Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-55

Run MEX File You Receive from Someone Else . . . . . . . . . . . . . . . . . . . . 7-56

Document Build Information in the MEX File . . . . . . . . . . . . . . . . . . . . . 7-57

MEX Version Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-59

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

MEX API Is Not Thread Safe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-61

Compiling MEX File Fails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-62


Build Example Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-62
Use Supported Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-62
File Not Found on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-62
Linux gcc -fPIC Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-62
Compiler Errors in Fortran MEX Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-62
Syntax Errors Compiling C/C++ MEX Files on UNIX . . . . . . . . . . . . . . . 7-62

Symbol mexFunction Unresolved or Not Defined . . . . . . . . . . . . . . . . . . . 7-64

MEX File Segmentation Fault . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-65

MEX File Generates Incorrect Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-66

Memory Management Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-67


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-67
Improperly Destroying an mxArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-67
Incorrectly Constructing a Cell or Structure mxArray . . . . . . . . . . . . . . . 7-68
Creating a Temporary mxArray with Improper Data . . . . . . . . . . . . . . . . 7-68
Creating Potential Memory Leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-69
Improperly Destroying a Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-69
Destroying Memory in a C++ Class Destructor . . . . . . . . . . . . . . . . . . . . 7-70

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

User Messages in C MEX Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4

Error Handling in C MEX Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5

Create C++ MEX Functions with C Matrix API . . . . . . . . . . . . . . . . . . . . . . 8-6


Creating Your C++ Source File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6
Compiling and Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6
Memory Considerations for Class Destructors . . . . . . . . . . . . . . . . . . . . . . 8-6
Use mexPrintf to Print to MATLAB Command Window . . . . . . . . . . . . . . . 8-6
C++ Class Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7
C++ File Handling Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7

xix
Create C Source MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9

Tables of MEX Function Source Code Examples . . . . . . . . . . . . . . . . . . . . 8-14


Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-14
C, C++, and Fortran MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-14
C MEX Functions Calling Fortran Subroutines . . . . . . . . . . . . . . . . . . . . 8-17

Choose a C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19


Select Microsoft Visual Studio Compiler . . . . . . . . . . . . . . . . . . . . . . . . . 8-19
Select MinGW-w64 Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19

Pass Scalar Values in C MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-20


Pass Scalar as Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-20
Pass Scalar by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-21

Pass Strings in C MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-22

C Matrix API String Handling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 8-24


How MATLAB Represents Strings in MEX Files . . . . . . . . . . . . . . . . . . . 8-24
Character Encoding and Multibyte Encoding Schemes . . . . . . . . . . . . . . 8-24
Converting MATLAB Character Vector to C-Style String . . . . . . . . . . . . . 8-25
Converting C-Style String to MATLAB Character Vector . . . . . . . . . . . . . 8-25
Returning Modified Input String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-25
Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-25

Pass Structures and Cell Arrays in C MEX File . . . . . . . . . . . . . . . . . . . . . 8-26

Create 2-D Cell Array in C MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-27

Fill mxArray in C MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-28


Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-28
Copying Data Directly into an mxArray . . . . . . . . . . . . . . . . . . . . . . . . . . 8-28
Pointing to Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-28

Prompt User for Input in C MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-29

Handle Complex Data in C MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-30


Create Source File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-30
Create Gateway Routine and Verify Input and Output Parameters . . . . . . 8-30
Create Output mxArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-31
Create Computational Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-31
Call convec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-31
Build and Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-31

Handle 8-, 16-, 32-, and 64-Bit Data in C MEX File . . . . . . . . . . . . . . . . . 8-33

Manipulate Multidimensional Numerical Arrays in C MEX Files . . . . . . 8-34

Handle Sparse Arrays in C MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-35

Debug on Microsoft Windows Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . 8-36

Debug on Linux Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-37

xx Contents
Debug on Mac Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
Using Xcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
Using LLDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-41

Handling Large mxArrays in C MEX Files . . . . . . . . . . . . . . . . . . . . . . . . . 8-43


Using the 64-Bit API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-43
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44
Caution Using Negative Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44
Building Cross-Platform Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44

Typed Data Access in C MEX Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-45

Persistent mxArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-47

Automatic Cleanup of Temporary Arrays in MEX Files . . . . . . . . . . . . . . 8-48


Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-48

Handling Large File I/O in MEX Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-50


Prerequisites to Using 64-Bit I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-50
Specifying Constant Literal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-51
Opening a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-51
Printing Formatted Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-52
Replacing fseek and ftell with 64-Bit Functions . . . . . . . . . . . . . . . . . . . . 8-52
Determining the Size of an Open File . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-52
Determining the Size of a Closed File . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-53

MinGW-w64 Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-54


Install MinGW-w64 Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-54
Building yprime.c Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-54
MinGW Installation Folder Cannot Contain Space . . . . . . . . . . . . . . . . . . 8-54
Updating MEX Files to Use MinGW Compiler . . . . . . . . . . . . . . . . . . . . . 8-54

Troubleshooting and Limitations Compiling C/C++ MEX Files with


MinGW-w64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-56
Do Not Link to Library Files Compiled with Non-MinGW Compilers . . . . 8-56
MinGW Installation Folder Cannot Contain Space . . . . . . . . . . . . . . . . . . 8-56
MEX Command Does not Choose MinGW . . . . . . . . . . . . . . . . . . . . . . . . 8-56
Manually Configure MinGW for MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 8-56
MinGW Behaves Similarly to gcc/g++ on Linux . . . . . . . . . . . . . . . . . . . 8-56
Potential Memory Leak Inside C++ MEX Files on Using MEX Exceptions
..................................................... 8-57
Unhandled Explicit Exceptions in C++ MEX Files Unexpectedly Terminate
MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-57

C++ MEX Applications


9
C++ MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
C++ MEX API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Basic Design of C++ MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Call MEX Function from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Examples of C++ MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3

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

Build C++ MEX Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8


Supported Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8
Build .cpp File with mex Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8
MEX Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8
File Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8

Test Your Build Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-10

C++ MEX API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-11


matlab::mex::Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-11
matlab::mex::ArgumentList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-11
C++ Engine API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-11
matlab::engine::MATLABEngine::feval . . . . . . . . . . . . . . . . . . . . . . . . . . 9-12
matlab::engine::MATLABEngine::fevalAsync . . . . . . . . . . . . . . . . . . . . . . 9-14
matlab::engine::MATLABEngine::eval . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-15
matlab::engine::MATLABEngine::evalAsync . . . . . . . . . . . . . . . . . . . . . . 9-16
matlab::engine::MATLABEngine::getVariable . . . . . . . . . . . . . . . . . . . . . 9-16
matlab::engine::MATLABEngine::getVariableAsync . . . . . . . . . . . . . . . . . 9-17
matlab::engine::MATLABEngine::setVariable . . . . . . . . . . . . . . . . . . . . . 9-17
matlab::engine::MATLABEngine::setVariableAsync . . . . . . . . . . . . . . . . . 9-18
matlab::engine::MATLABEngine::getProperty . . . . . . . . . . . . . . . . . . . . . 9-18
matlab::engine::MATLABEngine::getPropertyAsync . . . . . . . . . . . . . . . . 9-19
matlab::engine::MATLABEngine::setProperty . . . . . . . . . . . . . . . . . . . . . 9-20
matlab::engine::MATLABEngine::setPropertyAsync . . . . . . . . . . . . . . . . 9-21
Exception Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-21

Structure of C++ MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-23


MEX Function Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-23
Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-23
Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-23
Entry Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-23
Passing Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-23
Class Constructor and Destructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-24

Managing External Resources from MEX Functions . . . . . . . . . . . . . . . . 9-26


Reading a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-26

Handling Inputs and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-29


Argument Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-29
ArgumentList Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-30
Support Variable Number of Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 9-30

Data Access in Typed, Cell, and Structure Arrays . . . . . . . . . . . . . . . . . . . 9-32


Shared Copies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-32

xxii Contents
Modify Cell Array in MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-32
Modify Structure in MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-34

Data Types for Passing MEX Function Data . . . . . . . . . . . . . . . . . . . . . . . 9-37


Typed Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-37
Character Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-37
String Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-37
Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-38
Structure Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-38
MATLAB Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-38

Call MATLAB Functions from MEX Functions . . . . . . . . . . . . . . . . . . . . . 9-40


Single Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-40
Multiple Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-40

Catch Exceptions in MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-42

Execute MATLAB Statements from MEX Function . . . . . . . . . . . . . . . . . . 9-43

Set and Get MATLAB Variables from MEX . . . . . . . . . . . . . . . . . . . . . . . . 9-44


Get Variable from MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . 9-44
Put Variable in MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-44
Set and Get Variable Example Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-45

MATLAB Objects in MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-46


Get Property Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-46
Get Property Value from Object Array . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-46
Set Property Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-46
Set Property Value in Object Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-47
Object Property Copy-On-Write Behavior . . . . . . . . . . . . . . . . . . . . . . . . 9-47
Modify Property and Return Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-47
Only Modified Property Causes Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-48
Handle Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-49

Avoid Copies of Arrays in MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . 9-51


Input Array Not Modified . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-51
Input Array Modified . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-51

Displaying Output in MATLAB Command Window . . . . . . . . . . . . . . . . . . 9-54

Using MEX Functions for MATLAB Class Methods . . . . . . . . . . . . . . . . . . 9-56


Method to Multiply Matrix by Scalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-56

Call MATLAB from Separate Threads in MEX Function . . . . . . . . . . . . . . 9-59


Communicating with MATLAB from Separate Threads . . . . . . . . . . . . . . 9-59
Example to Update the Display of Text . . . . . . . . . . . . . . . . . . . . . . . . . . 9-59

Out-of-Process Execution of C++ MEX Functions . . . . . . . . . . . . . . . . . . 9-62


How to Run Out of Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-62
Running arrayProduct MEX Function Out of Process . . . . . . . . . . . . . . . 9-62
Process Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-63
Getting Information About the MEX Host Process . . . . . . . . . . . . . . . . . . 9-63
Always Run Out of Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-63
Debugging Out-of-Process MEX Functions . . . . . . . . . . . . . . . . . . . . . . . 9-65

xxiii
Making async Requests Using mexCallMATLAB . . . . . . . . . . . . . . . . . . . . 9-68

Fortran MEX Files


10
Components of Fortran MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
mexFunction Gateway Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Naming the MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Difference Between .f and .F Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Required Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Managing Input and Output Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 10-3
Validating Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-3
Computational Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-3

MATLAB Fortran API Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4


Matrix Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4
MEX Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4
Preprocessor Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4
Using the Fortran %val Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4

Data Flow in Fortran MEX Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6


Showing Data Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6
Gateway Routine Data Flow Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6

User Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-8

Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-9

Build Fortran MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10

Create Fortran Source MEX File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-11

Debug Fortran MEX Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-15


Notes on Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-15
Debugging on Microsoft Windows Platforms . . . . . . . . . . . . . . . . . . . . . 10-15
Debugging on Linux Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-15

Handling Large mxArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-17


Using the 64-Bit API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-17
Caution Using Negative Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-18
Building Cross-Platform Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 10-18

Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-20

MATLAB Supports Fortran 77 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-21

Handle Complex Fortran Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-22


Build and Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-22

xxiv Contents
Calling MATLAB Engine from C/C++ and Fortran Programs
11
Choosing Engine Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2

Introducing MATLAB Engine APIs for C and Fortran . . . . . . . . . . . . . . . . 11-3


Communicating with MATLAB Software . . . . . . . . . . . . . . . . . . . . . . . . . 11-3

Callbacks in Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-5

Call MATLAB Functions from C Applications . . . . . . . . . . . . . . . . . . . . . . 11-6

Call MATLAB Functions from Fortran Applications . . . . . . . . . . . . . . . . . 11-8

Attach to Existing MATLAB Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-9

Build Windows Engine Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-10

Run Windows Engine Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-11

Build and Run Fortran Engine Applications on Windows . . . . . . . . . . . 11-12

Set Run-Time Library Path on Windows Systems . . . . . . . . . . . . . . . . . . 11-14


Change Path Each Time You Run the Application . . . . . . . . . . . . . . . . . 11-14
Permanently Change Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-14
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-14

Register MATLAB as a COM Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-15

Build Engine Application on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-16

Build Engine Application on macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-17

Run Engine Application on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-18

Build and Run Fortran Engine Applications on Linux . . . . . . . . . . . . . . 11-19

Run Engine Application on macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-20

Build and Run Fortran Engine Applications on macOS . . . . . . . . . . . . . 11-21

Set Run-Time Library Path on Linux Systems . . . . . . . . . . . . . . . . . . . . . 11-22


C Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22
Bourne Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22

Set Run-Time Library Path on macOS Systems . . . . . . . . . . . . . . . . . . . . 11-23


C Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-23
Bourne Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-23

Build Engine Applications with IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-24


Configuring the IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-24
Engine Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-24
Engine Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-24

xxv
Can't Start MATLAB Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-26

Multithreaded Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-27

User Input Not Supported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-28

Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-29

Write Fortran Engine Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-30

Debug MATLAB Function Called by C Engine . . . . . . . . . . . . . . . . . . . . . 11-31


Debug Engine Application on Windows . . . . . . . . . . . . . . . . . . . . . . . . . 11-31
Debug Engine Application Attached to Existing MATLAB Session . . . . . 11-31

Engine API for Java


12
MATLAB Engine API for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2

Build Java Engine Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3


General Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3
Compile and Run Java Code on Windows . . . . . . . . . . . . . . . . . . . . . . . . 12-3
Compile and Run Java Code on macOS . . . . . . . . . . . . . . . . . . . . . . . . . . 12-4
Compile and Run Java Code on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-4

Java Example Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-6

Java Engine API Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7


com.mathworks Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7
com.mathworks.engine.MatlabEngine Methods . . . . . . . . . . . . . . . . . . . 12-7
java.util.concurrent.Future Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-8

Java Data Type Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-9


Pass Java Data to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-9
Pass MATLAB Data to Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-9

Start and Close MATLAB Session from Java . . . . . . . . . . . . . . . . . . . . . . 12-11


Start MATLAB Synchronously . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-11
Start MATLAB Asynchronously . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-11
Start Engine with Startup Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-11
Close MATLAB Engine Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-12

Connect Java to Running MATLAB Session . . . . . . . . . . . . . . . . . . . . . . . 12-14


Find and Connect to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-14
Connect to MATLAB Synchronously . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-14
Connect to MATLAB Asynchronously . . . . . . . . . . . . . . . . . . . . . . . . . . 12-15
Specify Name of Shared Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-15

Execute MATLAB Functions from Java . . . . . . . . . . . . . . . . . . . . . . . . . . 12-16


Calling MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-16
Execute Function with Single Returned Argument . . . . . . . . . . . . . . . . 12-16
Execute Function with Multiple Returned Arguments . . . . . . . . . . . . . . 12-16

xxvi Contents
When to Specify Number of Output Arguments . . . . . . . . . . . . . . . . . . . 12-17

Evaluate MATLAB Statements from Java . . . . . . . . . . . . . . . . . . . . . . . . . 12-18


Evaluating MATLAB Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-18
Evaluate Mathematical Function in MATLAB . . . . . . . . . . . . . . . . . . . . 12-18

Pass Variables from Java to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-19


Ways to Pass Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-19
Pass Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-19
Put Variables in the MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . 12-19

Pass Variables from MATLAB to Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-21


Coordinate Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-21

Using Complex Variables in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-22


Complex Variables in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-22
Get Complex Variables from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 12-22
Pass Complex Variable to MATLAB Function . . . . . . . . . . . . . . . . . . . . . 12-23

Using MATLAB Structures in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-24


MATLAB Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-24
Pass Struct to MATLAB Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-24
Get Struct from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-25

Pass Java CellStr to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-26


MATLAB Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-26
Create CellStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-26

Using MATLAB Handle Objects in Java . . . . . . . . . . . . . . . . . . . . . . . . . . 12-27


MATLAB Handle Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-27
Java HandleObject Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-27
Set Graphics Object Properties from Java . . . . . . . . . . . . . . . . . . . . . . . 12-27

Redirect MATLAB Command Window Output to Java . . . . . . . . . . . . . . 12-29


Output to MATLAB Command Window . . . . . . . . . . . . . . . . . . . . . . . . . 12-29
Redirect MATLAB Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-29
Redirect MATLAB Error Messages to Java . . . . . . . . . . . . . . . . . . . . . . 12-29

Run Simulink Simulation from Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-31


MATLAB Command to Run Simulation . . . . . . . . . . . . . . . . . . . . . . . . . 12-31
Run vdp Model from Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-31

MATLAB Engine API Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-33


com.mathworks.engine.EngineException . . . . . . . . . . . . . . . . . . . . . . . 12-33
com.mathworks.engine.UnsupportedTypeException . . . . . . . . . . . . . . . 12-33
com.mathworks.engine.MatlabExecutionException . . . . . . . . . . . . . . . . 12-33
com.mathworks.engine.MatlabSyntaxException . . . . . . . . . . . . . . . . . . 12-33

Pass Java Array Arguments to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 12-34


2-D Array Arguments for MATLAB Functions . . . . . . . . . . . . . . . . . . . . 12-34
Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-34

Incorrect Java Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-36


Java String to MATLAB Character Vector . . . . . . . . . . . . . . . . . . . . . . . 12-36
Setting Graphics Object Properties from Java . . . . . . . . . . . . . . . . . . . . 12-36

xxvii
Java Integer to MATLAB double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-37

Incorrect Number of Output Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 12-38

MATLAB Engine for Python Topics


13
Get Started with MATLAB Engine API for Python . . . . . . . . . . . . . . . . . . 13-2

Install MATLAB Engine API for Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4


Verify Your Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Install the Engine API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Start MATLAB Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Install Python Engine for Multiple MATLAB Versions . . . . . . . . . . . . . . . 13-5
Start Specific MATLAB Engine Version . . . . . . . . . . . . . . . . . . . . . . . . . . 13-5
Troubleshooting MATLAB Engine API for Python Installation . . . . . . . . . 13-5

Install MATLAB Engine API for Python in Nondefault Locations . . . . . . 13-7


Build or Install in Nondefault Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-7
Install Engine in Your Home Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-7

Start and Stop MATLAB Engine for Python . . . . . . . . . . . . . . . . . . . . . . . . 13-9


Start MATLAB Engine for Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-9
Run Multiple Engines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-9
Stop Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-9
Start Engine with Startup Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-9
Start Engine Asynchronously . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-10

Connect Python to Running MATLAB Session . . . . . . . . . . . . . . . . . . . . 13-11


Connect to Shared MATLAB Session . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-11
Connect Asynchronously to Shared MATLAB Session . . . . . . . . . . . . . . 13-11
Connect to Multiple Shared MATLAB Sessions . . . . . . . . . . . . . . . . . . . 13-12
Start Shared MATLAB Sessions with Startup Options . . . . . . . . . . . . . . 13-12

Call MATLAB Functions from Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-13


Return Output Argument from MATLAB Function . . . . . . . . . . . . . . . . . 13-13
Return Multiple Output Arguments from MATLAB Function . . . . . . . . . 13-13
Return No Output Arguments from MATLAB Function . . . . . . . . . . . . . 13-13
Stop Execution of Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-14
Use Function Names for MATLAB Operators . . . . . . . . . . . . . . . . . . . . 13-14

Call MATLAB Functions Asynchronously from Python . . . . . . . . . . . . . . 13-15

Call User Scripts and Functions from Python . . . . . . . . . . . . . . . . . . . . . 13-16

Redirect Standard Output and Error to Python . . . . . . . . . . . . . . . . . . . 13-17

Use MATLAB Handle Objects in Python . . . . . . . . . . . . . . . . . . . . . . . . . 13-18

Use MATLAB Engine Workspace in Python . . . . . . . . . . . . . . . . . . . . . . . 13-20

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

Handle Data Returned from MATLAB to Python . . . . . . . . . . . . . . . . . . 13-23


MATLAB Scalar Type to Python Type Mapping . . . . . . . . . . . . . . . . . . . 13-23
MATLAB Array Type to Python Type Mapping . . . . . . . . . . . . . . . . . . . . 13-24
Unsupported MATLAB Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-24

MATLAB Arrays as Python Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-25


Create MATLAB Arrays in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-25
MATLAB Array Attributes and Methods in Python . . . . . . . . . . . . . . . . . 13-26
Multidimensional MATLAB Arrays in Python . . . . . . . . . . . . . . . . . . . . . 13-26
Index Into MATLAB Arrays in Python . . . . . . . . . . . . . . . . . . . . . . . . . . 13-27
Slice MATLAB Arrays in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-27
Reshape MATLAB Arrays in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-28

Use MATLAB Arrays in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-29

Sort and Plot MATLAB Data from Python . . . . . . . . . . . . . . . . . . . . . . . . 13-31

Get Help for MATLAB Functions from Python . . . . . . . . . . . . . . . . . . . . 13-34


How to Find MATLAB Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-34
Open MATLAB Help Browser from Python . . . . . . . . . . . . . . . . . . . . . . 13-34
Display MATLAB Help at Python Prompt . . . . . . . . . . . . . . . . . . . . . . . . 13-35

Default Numeric Types in MATLAB and Python . . . . . . . . . . . . . . . . . . . 13-36

System Requirements for MATLAB Engine API for Python . . . . . . . . . . 13-37


Python Version Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-37
Download 64-Bit Versions of Python and MATLAB . . . . . . . . . . . . . . . . . 13-37
Requirements for Building Python from Source . . . . . . . . . . . . . . . . . . 13-38

Limitations to MATLAB Engine API for Python . . . . . . . . . . . . . . . . . . . 13-39

Troubleshoot MATLAB Errors in Python . . . . . . . . . . . . . . . . . . . . . . . . . 13-40


MATLAB Errors in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-40
MatlabExecutionError: Undefined Function . . . . . . . . . . . . . . . . . . . . . 13-40
SyntaxError: Expression Not Valid Target . . . . . . . . . . . . . . . . . . . . . . . 13-40
SyntaxError: Invalid Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-41
Cannot Find MATLAB Session in Python . . . . . . . . . . . . . . . . . . . . . . . . 13-41

Engine API for C++


14
Introduction to Engine API for C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
Basic Elements of C++ Engine Programs . . . . . . . . . . . . . . . . . . . . . . . . 14-2

C++ Engine API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-4


Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-4

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

Build C++ Engine Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-7


Supported Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-7
Build .cpp File with mex Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-7
General Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-7
Engine Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-8
Runtime Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-8

Test Your Build Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-9

Start MATLAB Sessions from C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-11


Start MATLAB Session Synchronously . . . . . . . . . . . . . . . . . . . . . . . . . 14-11
Start MATLAB Session Asynchronously . . . . . . . . . . . . . . . . . . . . . . . . . 14-11
Start MATLAB with Startup Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-11

Connect C++ to Running MATLAB Session . . . . . . . . . . . . . . . . . . . . . . 14-13


Connect to Shared MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-13
Connect to Shared MATLAB Asynchronously . . . . . . . . . . . . . . . . . . . . 14-13
Specify Name of Shared Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-14
Find and Connect to Named Shared Session . . . . . . . . . . . . . . . . . . . . . 14-14

Call MATLAB Functions from C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-16


Call Function with Single Returned Argument . . . . . . . . . . . . . . . . . . . 14-16
Call Function with Name/Value Arguments . . . . . . . . . . . . . . . . . . . . . . 14-18
Call Function Asynchronously . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-19
Call Function with Multiple Returned Arguments . . . . . . . . . . . . . . . . . 14-19
Call Function with Native C++ Types . . . . . . . . . . . . . . . . . . . . . . . . . . 14-20
Control Number of Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-21

Evaluate MATLAB Statements from C++ . . . . . . . . . . . . . . . . . . . . . . . . 14-23


Evaluation of MATLAB Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-23
Evaluate Mathematical Function in MATLAB . . . . . . . . . . . . . . . . . . . . 14-23

Pass Variables from C++ to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-25


Ways to Pass Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-25
Put Variables in MATLAB Base Workspace . . . . . . . . . . . . . . . . . . . . . . 14-25

Pass Variables from MATLAB to C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-27


Bring Result of MATLAB Calculation Into C++ . . . . . . . . . . . . . . . . . . . 14-27
Get MATLAB Objects and Access Properties . . . . . . . . . . . . . . . . . . . . . 14-27
Set Property on MATLAB Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-28

Redirect MATLAB Command Window Output to C++ . . . . . . . . . . . . . . 14-30


Redirect Screen Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-30
Redirect Error Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-30

Create Cell Arrays from C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-32


Put Cell Array in MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . 14-32
Access Elements of Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-33
Modify Elements of Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-33

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

Pass Enumerations to MATLAB From C++ . . . . . . . . . . . . . . . . . . . . . . . 14-39

Pass Sparse Arrays to MATLAB From C++ . . . . . . . . . . . . . . . . . . . . . . . 14-41

Run Simulink Simulation from C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-42


MATLAB Command to Run Simulation . . . . . . . . . . . . . . . . . . . . . . . . . 14-42
Simulink vdp Model from C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-42
MATLAB Code to Run Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-42
C++ Code to Run Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-43

Convert C++ Engine Application to MATLAB Compiler SDK Application


........................................................ 14-45
Applications to Call Sierpinski Function . . . . . . . . . . . . . . . . . . . . . . . . 14-45

Using .NET Libraries from MATLAB


15
Read Cell Arrays of Excel Spreadsheet Data . . . . . . . . . . . . . . . . . . . . . . . 15-3

Access a Simple .NET Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-5


System.DateTime Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-5
Create .NET Object from Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-5
View Information About .NET Object . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-6
Introduction to .NET Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-7

Load a Global .NET Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-9

Work with Microsoft Excel Spreadsheets Using .NET . . . . . . . . . . . . . . 15-10

Work with Microsoft Word Documents Using .NET . . . . . . . . . . . . . . . . 15-12

Assembly Is Library of .NET Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-13

Limitations to .NET Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-14

System Requirements for Using MATLAB Interface to .NET . . . . . . . . . 15-15


MATLAB Configuration File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-15

Using .NET from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-16


Benefits of the MATLAB .NET Interface . . . . . . . . . . . . . . . . . . . . . . . . 15-16
Why Use the MATLAB .NET Interface? . . . . . . . . . . . . . . . . . . . . . . . . . 15-16
NET Assembly Integration Using MATLAB Compiler SDK . . . . . . . . . . . 15-16
To Learn More About the .NET Framework . . . . . . . . . . . . . . . . . . . . . . 15-17

Using a .NET Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-18


Creating a .NET Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-18
What Classes Are in a .NET Assembly? . . . . . . . . . . . . . . . . . . . . . . . . . 15-18

xxxi
Using the delete Function on a .NET Object . . . . . . . . . . . . . . . . . . . . . 15-18

Build a .NET Application for MATLAB Examples . . . . . . . . . . . . . . . . . . 15-20

Troubleshooting Security Policy Settings from Network Drives . . . . . . 15-21

.NET Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-22


.NET Framework System Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . 15-22
Reference Type Versus Value Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-22

Simplify .NET Class Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-23

Use import in MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-24

Use .NET Nested Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-25

Handle .NET Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-26

Pass Numeric Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-27


Call .NET Methods with Numeric Arguments . . . . . . . . . . . . . . . . . . . . 15-27
Use .NET Numeric Types in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 15-27

Pass System.String Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-28


Call .NET Methods with System.String Arguments . . . . . . . . . . . . . . . . 15-28
Use System.String in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-28

Pass System.Enum Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-30


Call .NET Methods with System.Enum Arguments . . . . . . . . . . . . . . . . 15-30
Use System.Enum in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-30

Pass System.Nullable Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-32

Pass Cell Arrays of .NET Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-36


Example of Cell Arrays of .NET Data . . . . . . . . . . . . . . . . . . . . . . . . . . 15-36
Create a Cell Array for Each System.Object . . . . . . . . . . . . . . . . . . . . . 15-36
Create MATLAB Variables from the .NET Data . . . . . . . . . . . . . . . . . . . 15-37
Call MATLAB Functions with MATLAB Variables . . . . . . . . . . . . . . . . . . 15-37

Pass Jagged Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-38


Create System.Double .NET Jagged Array . . . . . . . . . . . . . . . . . . . . . . 15-38
Call .NET Method with System.String Jagged Array Arguments . . . . . . 15-38
Call .NET Method with Multidimensional Jagged Array Arguments . . . . 15-39

Convert Nested System.Object Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-41

Pass Data to .NET Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-42


Pass Primitive .NET Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-42
Pass Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-43
Pass Nonprimitive .NET Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-43
Pass MATLAB String and Character Data . . . . . . . . . . . . . . . . . . . . . . . 15-43
Pass System.Nullable Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-43
Pass NULL Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-44
Unsupported MATLAB Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-44
Choosing Method Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-44
Example — Choosing a Method Signature . . . . . . . . . . . . . . . . . . . . . . . 15-45

xxxii Contents
Pass Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-46
Pass MATLAB Arrays as Jagged Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 15-46

Handle Data Returned from .NET Objects . . . . . . . . . . . . . . . . . . . . . . . 15-47


.NET Type to MATLAB Type Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . 15-47
Convert Arrays of Primitive .NET Type to MATLAB Type . . . . . . . . . . . . 15-48
How MATLAB Handles System.String . . . . . . . . . . . . . . . . . . . . . . . . . . 15-48
How MATLAB Handles System.__ComObject . . . . . . . . . . . . . . . . . . . . 15-49
How MATLAB Handles System.Nullable . . . . . . . . . . . . . . . . . . . . . . . . 15-50
How MATLAB Handles dynamic Type . . . . . . . . . . . . . . . . . . . . . . . . . . 15-50
How MATLAB Handles Jagged Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 15-50

Use Arrays with .NET Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-51


Pass MATLAB Arrays to .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-51
Convert Primitive .NET Arrays to MATLAB Arrays . . . . . . . . . . . . . . . . 15-51
Access .NET Array Elements in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 15-51
Convert .NET Jagged Arrays to MATLAB Arrays . . . . . . . . . . . . . . . . . . 15-52

Convert .NET Arrays to Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-53


Convert Nested System.Object Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 15-53
cell Function Syntax for System.Object[,] Arrays . . . . . . . . . . . . . . . . . 15-54

Limitations to Support of .NET Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 15-55

Set Static .NET Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-56


Set System.Environment.CurrentDirectory Static Property . . . . . . . . . . 15-56
Do Not Use ClassName.PropertyName Syntax for Static Properties . . . 15-56

Using .NET Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-58


How MATLAB Represents .NET Properties . . . . . . . . . . . . . . . . . . . . . . 15-58
How MATLAB Maps C# Property and Field Access Modifiers . . . . . . . . 15-58

MATLAB Does Not Display Protected Properties . . . . . . . . . . . . . . . . . . 15-60

Work with .NET Methods Having Multiple Signatures . . . . . . . . . . . . . 15-61


Display Function Signature Example . . . . . . . . . . . . . . . . . . . . . . . . . . 15-61

Call .NET Methods With out Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-63

Call .NET Methods With ref Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-65

Call .NET Methods With params Keyword . . . . . . . . . . . . . . . . . . . . . . . . 15-67

Call .NET Methods with Optional Arguments . . . . . . . . . . . . . . . . . . . . . 15-69


Skip Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-69
Call Overloaded Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-70

Calling .NET Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-72


Getting Method Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-72
C# Method Access Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-72
VB.NET Method Access Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-72
Reading Method Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-73

Calling .NET Methods with Optional Arguments . . . . . . . . . . . . . . . . . . 15-74


Skipping Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-74

xxxiii
Determining Which Overloaded Method Is Invoked . . . . . . . . . . . . . . . . 15-74
Support for ByRef Attribute in VB.NET . . . . . . . . . . . . . . . . . . . . . . . . . 15-74

Calling .NET Extension Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-75

Call .NET Properties That Take an Argument . . . . . . . . . . . . . . . . . . . . . 15-76

How MATLAB Represents .NET Operators . . . . . . . . . . . . . . . . . . . . . . . 15-77

Limitations to Support of .NET Methods . . . . . . . . . . . . . . . . . . . . . . . . . 15-78


Displaying Generic Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-78
Overloading MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-78
Calling Overloaded Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-78

Use .NET Events in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-79


Monitor Changes to .TXT File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-79
Monitor Changes to Windows Form ComboBox . . . . . . . . . . . . . . . . . . . 15-79

Call .NET Delegates in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-81


Declare a Delegate in a C# Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . 15-81
Load the Assembly Containing the Delegate into MATLAB . . . . . . . . . . 15-81
Select a MATLAB Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-81
Create an Instance of the Delegate in MATLAB . . . . . . . . . . . . . . . . . . . 15-81
Invoke the Delegate Instance in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 15-81

Create Delegates from .NET Object Methods . . . . . . . . . . . . . . . . . . . . . 15-83

Create Delegate Instances Bound to .NET Methods . . . . . . . . . . . . . . . 15-84


Example — Create a Delegate Instance Associated with a .NET Object
Instance Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-84
Example — Create a Delegate Instance Associated with a Static .NET
Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-84

.NET Delegates With out and ref Type Arguments . . . . . . . . . . . . . . . . . 15-86

Combine and Remove .NET Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-87

.NET Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-89

Calling .NET Methods Asynchronously . . . . . . . . . . . . . . . . . . . . . . . . . . 15-90


How MATLAB Handles Asynchronous Method Calls in .NET . . . . . . . . . 15-90
Using EndInvoke With out and ref Type Arguments . . . . . . . . . . . . . . . 15-90
Using Polling to Detect When Asynchronous Call Finishes . . . . . . . . . . 15-90

Limitations to Support of .NET Events . . . . . . . . . . . . . . . . . . . . . . . . . . 15-91


MATLAB Support of Standard Signature of an Event Handler Delegate
.................................................... 15-91

Limitations to Support of .NET Delegates . . . . . . . . . . . . . . . . . . . . . . . . 15-92

Use Bit Flags with .NET Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . 15-93


How MATLAB Supports Bitwise Operations on System.Enum . . . . . . . . 15-93
Creating .NET Enumeration Bit Flags . . . . . . . . . . . . . . . . . . . . . . . . . . 15-93
Removing a Flag from a Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-94
Replacing a Flag in a Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-94

xxxiv Contents
Testing for Membership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-94

Read Special System Folder Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-96

Default Methods for an Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-97

NetDocEnum Example Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-99

Work with Members of a .NET Enumeration . . . . . . . . . . . . . . . . . . . . . 15-100

Refer to a .NET Enumeration Member . . . . . . . . . . . . . . . . . . . . . . . . . 15-102


Using the Implicit Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-102

Display .NET Enumeration Members as Character Vectors . . . . . . . . . 15-103

Convert .NET Enumeration Values to Type Double . . . . . . . . . . . . . . . . 15-104

Iterate Through a .NET Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . 15-105


Information About System.Enum Methods . . . . . . . . . . . . . . . . . . . . . 15-105
Display Enumeration Member Names . . . . . . . . . . . . . . . . . . . . . . . . . 15-105

Use .NET Enumerations to Test for Conditions . . . . . . . . . . . . . . . . . . 15-107


Using Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-107
Using Relational Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-107

Underlying Enumeration Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-109

Limitations to Support of .NET Enumerations . . . . . . . . . . . . . . . . . . . 15-110

Create .NET Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-111

Convert .NET Collections to MATLAB Arrays . . . . . . . . . . . . . . . . . . . . 15-113

Create .NET Arrays of Generic Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-114

Display .NET Generic Methods Using Reflection . . . . . . . . . . . . . . . . . 15-115


showGenericMethods Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-115
Display Generic Methods in a Class . . . . . . . . . . . . . . . . . . . . . . . . . . 15-116
Display Generic Methods in a Generic Class . . . . . . . . . . . . . . . . . . . . 15-116

.NET Generic Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-118

Accessing Items in .NET Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-119

Call .NET Generic Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-120


Using the NetDocGeneric Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-120
Invoke Generic Class Member Function . . . . . . . . . . . . . . . . . . . . . . . 15-120
Invoke Static Generic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-121
Invoke Static Generic Functions of a Generic Class . . . . . . . . . . . . . . . 15-121
Invoke Generic Functions of a Generic Class . . . . . . . . . . . . . . . . . . . 15-121

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

Register Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-4


Access COM Controls Created with .NET . . . . . . . . . . . . . . . . . . . . . . . . 16-4
Verify Registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-4

Get Started with COM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-5


Create Instance of COM Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-5
Register Custom Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-5

Read Spreadsheet Data Using Excel as Automation Server . . . . . . . . . . . 16-6


Techniques Demonstrated . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-6
Create Excel Automation Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-6
Manipulate Data in MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . 16-7
Create Plotter Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-8
Insert MATLAB Graphs into Excel Spreadsheet . . . . . . . . . . . . . . . . . . . . 16-9
Run Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-10

Supported Client/Server Configurations . . . . . . . . . . . . . . . . . . . . . . . . . 16-11


MATLAB Client and In-Process Server . . . . . . . . . . . . . . . . . . . . . . . . . 16-11
MATLAB Client and Out-of-Process Server . . . . . . . . . . . . . . . . . . . . . . 16-11
COM Implementations Supported by MATLAB . . . . . . . . . . . . . . . . . . . 16-12
Client Application and MATLAB Automation Server . . . . . . . . . . . . . . . 16-12
Client Application and MATLAB Engine Server . . . . . . . . . . . . . . . . . . . 16-12

MATLAB COM Client Support


17
Create COM Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Instantiate DLL Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Instantiate EXE Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2

Handle COM Data in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-4


Pass Data to COM Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-4
Handle Data from COM Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-5
Unsupported Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-6
Pass MATLAB SAFEARRAY to COM Object . . . . . . . . . . . . . . . . . . . . . . . 17-6
Read SAFEARRAY from COM Objects in MATLAB Applications . . . . . . . . 17-8
Display MATLAB Syntax for COM Objects . . . . . . . . . . . . . . . . . . . . . . . . 17-8

COM Object Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10


MATLAB Functions for Object Properties . . . . . . . . . . . . . . . . . . . . . . . 17-10
Work with Multiple Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10

xxxvi Contents
Enumerated Values for Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10
Property Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10
Custom Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-11
Properties That Take Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-11

COM Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-12


Method Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-12
Call Object Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-12
Specify Enumerated Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-13
Skip Optional Input Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-13
Return Multiple Output Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-13

COM Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-14

COM Event Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-15


Arguments Passed to Event Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . 17-15
Event Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-15

COM Object Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-17


IUnknown and IDispatch Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-17

Save and Delete COM Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-19


Functions to Save and Restore COM Objects . . . . . . . . . . . . . . . . . . . . 17-19
Release COM Interfaces and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 17-19

MATLAB Application as DCOM Client . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-20

Explore COM Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-21


Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-21
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-21
Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-21
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-22
Identify Objects and Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-22

Change Row Height in Range of Spreadsheet Cells . . . . . . . . . . . . . . . . 17-24

Write Spreadsheet Data Using Excel as Automation Server . . . . . . . . . 17-26

Change Cursor in Spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-28

Insert Spreadsheet After First Sheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-29

Connect to Existing Excel Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-30

Display Message for Workbook OnClose Event . . . . . . . . . . . . . . . . . . . . 17-31

COM Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-32

MATLAB COM Support Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-33

Interpreting Argument Callouts in COM Error Messages . . . . . . . . . . . 17-34

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

MATLAB COM Automation Server Interface . . . . . . . . . . . . . . . . . . . . . . . 18-5


COM Server Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-5
Programmatic Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-5
Shared and Dedicated Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-5
In-Process and Out-of-Process Servers . . . . . . . . . . . . . . . . . . . . . . . . . . 18-6

Create MATLAB Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-8


Choose ProgID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-8
Create Automation Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-8
Connect to Existing MATLAB Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-9
Control MATLAB Appearance on Desktop . . . . . . . . . . . . . . . . . . . . . . . . 18-9

Manually Create Automation Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-11


Create Automation Server at MATLAB Command Prompt . . . . . . . . . . . 18-11
Create Automation Server at Startup . . . . . . . . . . . . . . . . . . . . . . . . . . 18-11
Add -automation Switch to MATLAB Shortcut Icon . . . . . . . . . . . . . . . . 18-11

Call MATLAB Function from Visual Basic .NET Client . . . . . . . . . . . . . . 18-13

Pass Complex Data to MATLAB from C# Client . . . . . . . . . . . . . . . . . . . 18-14

Call MATLAB Function from C# Client . . . . . . . . . . . . . . . . . . . . . . . . . . 18-15

Waiting for MATLAB Application to Complete . . . . . . . . . . . . . . . . . . . . 18-17

Convert MATLAB Types to COM Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-18


Variant Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-18
SAFEARRAY Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-19
VT_DATE Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-19
Unsupported Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-19

Convert COM Types to MATLAB Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-20

Using Web Services with MATLAB


19
Display Streamed Data in Figure Window . . . . . . . . . . . . . . . . . . . . . . . . . 19-2
PricesStreamer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-2
Map Data to MATLAB uitable Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-4
Display Data in JSON Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5
Terminate Data Stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5

xxxviii Contents
Call PricesStreamer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5

Display JPEG Images Streamed from IP Camera . . . . . . . . . . . . . . . . . . . 19-7


CameraPlayer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-7
Call CameraPlayer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-9

Send Multipart Form Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-10

Send and Receive HTTP Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-11

What Is the HTTP Interface? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-14

Manage Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-15

HTTP Data Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-16


Converting Data in Request Messages . . . . . . . . . . . . . . . . . . . . . . . . . 19-16
Converting Data in Response Messages . . . . . . . . . . . . . . . . . . . . . . . . 19-19
Supported Image Data Subtypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-21

Display Progress Monitor for HTTP Message . . . . . . . . . . . . . . . . . . . . . 19-22

Set Up WSDL Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-25

Display a World Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-26

Using WSDL Web Service with MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 19-30


What Are Web Services in MATLAB? . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-30
What Are WSDL Documents? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-30
What You Need to Use WSDL with MATLAB . . . . . . . . . . . . . . . . . . . . . 19-31

Access Services That Use WSDL Documents . . . . . . . . . . . . . . . . . . . . . . 19-32

Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-33


Considerations Using Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-33
Error Handling with try/catch Statements . . . . . . . . . . . . . . . . . . . . . . 19-33
Use a Local Copy of the WSDL Document . . . . . . . . . . . . . . . . . . . . . . . 19-33
Java Errors Accessing Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-33
Anonymous Types Not Supported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-34

XML-MATLAB Data Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-35

Limitations to WSDL Document Support . . . . . . . . . . . . . . . . . . . . . . . . 19-36


Unsupported WSDL Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-36
Documents Must Conform to Wrapper Style . . . . . . . . . . . . . . . . . . . . . 19-38
SOAP Header Fields Not Supported . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-38

Manually Redirect HTTP Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-39

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

Call Python Function in MATLAB to Wrap Paragraph Text . . . . . . . . . . . 20-6

Call User-Defined Python Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-8


Reload Modified User-Defined Python Module . . . . . . . . . . . . . . . . . . . . 20-9

Pass Python Function to Python map Function . . . . . . . . . . . . . . . . . . . 20-11

Access Elements in Python Container Types . . . . . . . . . . . . . . . . . . . . . . 20-12


Sequence Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-12
Mapping Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-12
Size and Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-12
Array Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-13
Use Zero-Based Indexing for Python Functions . . . . . . . . . . . . . . . . . . . 20-13
Limitations to Indexing into Python Objects . . . . . . . . . . . . . . . . . . . . . 20-13

Configure Your System to Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-15


Python Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-15
Install Supported Python Implementation . . . . . . . . . . . . . . . . . . . . . . . 20-15
Set Python Version on Windows Platform . . . . . . . . . . . . . . . . . . . . . . . 20-16
Set Python Version on Mac and Linux Platforms . . . . . . . . . . . . . . . . . . 20-16

MATLAB to Python Data Type Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . 20-17


Pass Scalar Values to Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-17
Pass Vectors to Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-18
Pass Matrices and Multidimensional Arrays to Python . . . . . . . . . . . . . 20-18
Automatically Convert Python Types to MATLAB Types . . . . . . . . . . . . 20-20
Explicitly Convert Python Types to MATLAB Types . . . . . . . . . . . . . . . . 20-20
Unsupported MATLAB Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-21

Troubleshooting Matrix and Numeric Argument Errors . . . . . . . . . . . . 20-23

Limitations to Python Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-24


Unsupported MATLAB Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-24

Unable to resolve the name py.myfunc . . . . . . . . . . . . . . . . . . . . . . . . . . 20-26


Python Not Installed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-26
64-bit/32-bit Versions of Python on Windows Platforms . . . . . . . . . . . . . 20-26
MATLAB Cannot Find Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-26
Error in User-Defined Python Module . . . . . . . . . . . . . . . . . . . . . . . . . . 20-26
Python Module Not on Python Search Path . . . . . . . . . . . . . . . . . . . . . . 20-27
Module Name Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-27

xl Contents
Python Tries to Execute myfunc in Wrong Module . . . . . . . . . . . . . . . . 20-27

Handle Python Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-28

Determine if Error is Python or MATLAB Error . . . . . . . . . . . . . . . . . . . 20-29


Python Error: Python class: message . . . . . . . . . . . . . . . . . . . . . . . . . . 20-29
Python Module Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-29
Errors Converting Python Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-29

Understand Python Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . 20-31


Positional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-31
Keyword Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-31
Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-32

Out-of-Process Execution of Python Functionality . . . . . . . . . . . . . . . . . 20-33


Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-34

Reload Out-of-Process Python Interpreter . . . . . . . . . . . . . . . . . . . . . . . 20-35

Use Python Numeric Variables in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 20-36

Use Python str Variables in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-39

Use Python list Variables in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-41

Use Python tuple Variables in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 20-45

Use Python dict Variables in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-47

Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-49


Understanding Python and MATLAB import Commands . . . . . . . . . . . . 20-49
Help for Python Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-49
Call Python Method With MATLAB Name Conflict . . . . . . . . . . . . . . . . . 20-50
Call Python eval Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-50
Execute Callable Python Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-51
How MATLAB Represents Python Operators . . . . . . . . . . . . . . . . . . . . . 20-51

Directly Call Python Functionality from MATLAB . . . . . . . . . . . . . . . . . 20-54


Access Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-54
Run Python Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-54
Run Python Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-54
Access to Python Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-54
Limitations to pyrun and pyrunfile Functions . . . . . . . . . . . . . . . . . . . . 20-55

System Commands
21
Shell Escape Function Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-2

Run External Commands, Scripts, and Programs . . . . . . . . . . . . . . . . . . . 21-3


Shell Escape Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3
Return Results and Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3

xli
Specify Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3
Run UNIX Programs off System Path . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-4
Run AppleScript on macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-5

Change Environment Variable for Shell Command . . . . . . . . . . . . . . . . . 21-6

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

Create Custom Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-5


Add and Remove Settings Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-5
Add and Remove Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-6
Validate Settings Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-7

Create Factory Settings for Toolboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-10


Create Factory Settings Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-10
Create Factory Settings JSON File . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-13
Test Factory Settings Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-14
Ensure Backward Compatibility Across Toolbox Versions . . . . . . . . . . . 22-15
Listen For Changes to Toolbox Settings . . . . . . . . . . . . . . . . . . . . . . . . 22-18

xlii Contents
1

External Programming Languages and


Systems
1 External Programming Languages and Systems

Integrate MATLAB with External Programming Languages and


Systems
MATLAB provides a flexible, two-way integration with other programming languages, allowing you to
reuse legacy code. For a list of programming languages and the supported versions, see MATLAB
Supported Interfaces to Other Languages.

Call C/C++ Code from MATLAB


MATLAB provides these features to help you integrate C/C++ algorithms into your MATLAB
applications.

• A C/C++ shared library interface is a collection of functions dynamically loaded by an application


at run time. Using a shared library has the advantage of packaging multiple library functions into
one interface. In addition, MATLAB manages data type conversions.

• 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

Use Objects from Other Programming Languages in MATLAB


If you have functions and objects in another programming language, you can call them from MATLAB.
You do not need to be a software developer to integrate these objects into your MATLAB application.
However, you need access to third-party documentation for the libraries.

MATLAB supports calling functions and using objects in the following languages.

• “C++ Libraries in MATLAB”


• “C Libraries in MATLAB”
• MEX File Functions for C/C++ and Fortran
• “Java Libraries in MATLAB”
• “Calling Python from MATLAB”
• “.NET Libraries in MATLAB”
• COM Objects

Call MATLAB from Another Programming Language


You can call MATLAB from another language using Engine Applications on page 11-2. Using
MATLAB engine APIs, call MATLAB functions from your own application. MATLAB has APIs for the
following languages.

• Engine API for C++


• Engine API for Java
• Engine API for Python
• Engine API for C
• Engine API for Fortran

To create an engine application, install a compiler that MATLAB supports and use the mex command
to build the application.

Call Your Functions as MATLAB Functions


You can write your own functions and call them as MATLAB functions using MEX APIs. For more
information, see “Choosing MEX Applications” on page 7-2. You can write MEX functions in the
following languages.

• C++ MEX APIs


• C MEX APIs
• Fortran MEX APIs

To create a MEX file, install a compiler that MATLAB supports and use the mex command to build the
function.

Communicate with Web Services


You can communicate with web services from MATLAB.

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

Custom Linking to Required API Libraries


MathWorks recommends that you use the mex command to build MEX files and engine applications.
This build script automatically links to the libraries required by the MATLAB APIs used in your
application.

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.

• Replace matlabroot with the value returned by matlabroot.


• Replace compiler with either microsoft or mingw64.
• The path to the include files is the value returned by:
fullfile(matlabroot,'extern','include')

C++ MEX Functions


To build C++ MEX functions, use the “C++ MEX API” on page 9-11 and “MATLAB Data API”.

Include files:

• mex.hpp — Definitions for the C++ MEX API


• mexAdapter.hpp — Utilities required by the C++ MEX function operator

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

C++ Engine Applications


To build C++ engine applications, use the “MATLAB Engine API for C++” and “MATLAB Data API”.

Include files:

• MatlabEngine.hpp — Definitions for the C++ engine API


• MatlabDataArray.hpp — Definitions for MATLAB Data Arrays

Windows libraries:

• Engine library — matlabroot\extern\lib\win64\compiler\libMatlabEngine.lib


• MATLAB Data Array library — matlabroot\extern\lib\win64\compiler
\libMatlabDataArray.lib

Linux libraries:

1-5
1 External Programming Languages and Systems

• Engine library — matlabroot/extern/bin/glnxa64/libMatlabEngine.so


• MATLAB Data Array library — matlabroot/extern/bin/glnxa64/libMatlabDataArray.so

macOS libraries:

• Engine library — matlabroot/extern/bin/maci64/libMatlabEngine.dylib


• MATLAB Data Array library — matlabroot/extern/bin/maci64/
libMatlabDataArray.dylib

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:

• mex.h — Declares the entry point and interface routines


• matrix.h — Definitions of the mxArray structure and function prototypes for matrix access
routines
• mat.h (optional) — Function prototypes for mat routines

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:

• engine.h — Function prototypes for engine routines

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:

• Engine library — matlabroot\extern\lib\win64\compiler\libeng.lib


• Matrix library — matlabroot\extern\lib\win64\compiler\libmx.lib
• MEX library (optional) — matlabroot\extern\lib\win64\compiler\libmex.lib
• MAT-File library (optional) — matlabroot\extern\lib\win64\compiler\libmat.lib

Linux libraries:

• Engine library — matlabroot/bin/glnxa64/libeng.so


• Matrix library — matlabroot/bin/glnxa64/libmx.so
• MEX library (optional) — matlabroot/bin/glnxa64/libmex.so
• MAT-File library (optional) — matlabroot/bin/glnxa64/libmat.so

macOS libraries:

• Engine library — matlabroot/bin/maci64/libeng.dylib


• Matrix library — matlabroot/bin/maci64/libmx.dylib
• MEX library (optional) — matlabroot/bin/maci64/libmex.dylib
• MAT-File library (optional) — matlabroot/bin/maci64/libmat.dylib

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:

• mat.h — Function prototypes for mat routines


• matrix.h — Definitions of the mxArray structure and function prototypes for matrix access
routines

Windows libraries:

• MAT-File library — matlabroot\extern\lib\win64\compiler\libmat.lib


• Matrix library — matlabroot\extern\lib\win64\compiler\libmx.lib
• MEX library (optional) — matlabroot\extern\lib\win64\compiler\libmex.lib

Linux libraries:

• MAT-File library — matlabroot/bin/glnxa64/libmat.so


• Matrix library — matlabroot/bin/glnxa64/libmx.so
• MEX library (optional) — matlabroot/extern/bin/glnxa64/libmex.so

1-7
1 External Programming Languages and Systems

macOS libraries:

• MAT-File library — matlabroot/bin/maci64/libmat.dylib


• Matrix library — matlabroot/bin/maci64/libmx.dylib
• MEX library (optional) — matlabroot/extern/bin/maci64/libmex.dylib

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

External Data Interface (EDI)

• “Create Arrays with C++ MATLAB Data API” on page 2-2


• “Copy C++ MATLAB Data Arrays” on page 2-4
• “C++ Cell Arrays” on page 2-5
• “Access C++ Data Array Container Elements” on page 2-6
• “Operate on C++ Arrays Using Visitor Pattern” on page 2-8
• “MATLAB Data API Exceptions” on page 2-12
• “MATLAB Data API Types” on page 2-16
2 External Data Interface (EDI)

Create Arrays with C++ MATLAB Data API


In this section...
“Create Arrays” on page 2-2
“Operate on Each Element in an Array” on page 2-3

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 header file for the MATLAB Data API is MatlabDataArray.hpp.

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.

To create an array, first create a factory using matlab::data::ArrayFactory.

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;
}

This code is equivalent to the following MATLAB statements.

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;

// Create a 3-by-2 TypedArray


TypedArray<double> A = factory.createArray( {3,2},
{1.1, 2.2, 3.3, 4.4, 5.5, 6.6 });

// Assign values of A to the double array C


double C[6];
int i = 0;
for (auto e : A) {
C[i++] = e;
}

return 0;
}

Operate on Each Element in an Array


Modify each element in a matlab::data::Array using a reference to the element. This example
multiplies each element in the matlab::data::TypedArray by a scalar value.

#include "MatlabDataArray.hpp"

int main() {
using namespace matlab::data;
ArrayFactory factory;

// Create a 3-by-2 TypedArray


TypedArray<double> A = factory.createArray( {3,2},
{1.1, 2.2, 3.3, 4.4, 5.5, 6.6 });

// Define scalar multiplier


double multiplier(10.2);

// Multiple each element in A


for (auto& elem : A) {
elem *= multiplier;
}

return 0;
}

See Also
createArray | matlab::data::TypedArray

2-3
2 External Data Interface (EDI)

Copy C++ MATLAB Data Arrays


The matlab::data::Array class supports both copy and move semantics. Copies of Array objects
create shared data copies. In the following C++ code, variables B and C are copies of
matlab::data::CharArray A; all three variables point to the same data.

#include "MatlabDataArray.hpp"

int main() {
using namespace matlab::data;
ArrayFactory factory;
CharArray A = factory.createCharArray("This is a char array.");

// Create a shared copy of A


CharArray B(A);

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.

// B becomes unshared once modified


B[20] = char16_t(33);

C++ MATLAB Data Arrays support move semantics. When you pass a variable using move, there is
no copy of the variable.

Avoid Unnecessary Data Copying


If you index into or use an iterator on an array for read-only purposes, then the best practice is to
declare the array as const. Otherwise, the API functions might create a copy of the array in
anticipation of a possible copy-on-write operation.

See Also
createCharArray

2-4
C++ Cell Arrays

C++ Cell Arrays


To create a cell array, use the matlab::data::ArrayFactory createCellArray function.

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}.

C[0][0] = factory.createCharArray("New Character Array");

Get a reference to the cell containing the double array and change the first element to -2.2.

TypedArrayRef<double> doubleArray = C[1][0];


doubleArray[0] = -2.2;

Display the new values in the cell containing the double array:

TypedArray<double> const newArray = C[1][0];


for (auto e : newArray) {
std::cout << e << std::endl;
}

See Also
matlab::data::ArrayFactory

Related Examples
• “Access C++ Data Array Container Elements” on page 2-6

2-5
2 External Data Interface (EDI)

Access C++ Data Array Container Elements


The C++ MATLAB Data API CellArray and StructArray types are containers for other MATLAB
Data Arrays. The elements in the containers are themselves arrays. There are two ways to access
these elements:

• Get a reference to the elements of the container.


• Get a shared copy of the elements of the container.

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;

auto cellArr = f.createCellArray({2,2},


f.createArray<bool>({1,3},{true, true, false}),
f.createCharArray("A char Array"),
f.createScalar<int32_t>(-3374),
f.createArray<double>({1,3},{2.2, 3.3, -4.2}));

// Get a reference to the first cell of the cell array.


TypedArrayRef<bool> ref = cellArr[0][0];

// Use the reference to modify the values in the cell.


for (auto& e : ref) {
e = false;
}

After running this code, the first element of the cell array is a 1-by-3 logical array with each element
set to false.

Copy Data from Container


You can access the data in a container using a shared copy. A shared copy enables you to get the data
from the container or to modify the data in a copy that becomes nonshared when modified. Changing
the data in a copy does not change the data in the container.

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;

auto cellArr = f.createCellArray({2,2},


f.createArray<bool>({1,3},{true, true, false}),
f.createCharArray("A cell Array"),
f.createScalar<int32_t>(-3374),
f.createArray<double>({1,3},{2.2, 3.3, -4.2}));

// Get a shared copy of the last element of the cell array.


TypedArray<double> cpy = cellArr[1][1];
cpy[0] = 5.5;

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)

Operate on C++ Arrays Using Visitor Pattern


The C++ MATLAB Data API supports the use of visitor classes via the
matlab::data::apply_visitor and matlab::data::apply_visitor_ref functions. These
functions accept an array or array reference and a visitor class as inputs.

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.

Use the visitor pattern in cases such as these:

• 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.

Dispatch on Array or Array Reference


The apply_visitor function dispatches to the visitor class operation based on the type of the input
array. The syntax for calling apply_visitor accepts a matlab::data::Array and your visitor
class instance:

auto apply_visitor(matlab::data::Array a, V visitor)

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:

auto apply_visitor_ref(const matlab::data::ArrayRef& a, V visitor)

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:

std::string operator()(matlab::data::CharArray arr){


return arr.toAscii();
}

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:

void operator()(TypedArrayRef<bool> boolArrRef) {


std::cout << "Negate logical value: " << std::endl;
for (auto &b : boolArrRef) {
b = !b;
}
}

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

Visitor Class to Display Contents of Cell Array


This example shows how to use a visitor class to define operations to perform on specific types of
matlab::data::Array.

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>

using namespace matlab::data;


void DisplayCell(const CellArray cellArray);

class DisplayVisitor {
public:
template <typename U>
void operator()(U arr) {}

void operator()(const TypedArray<bool> boolArr) {


std::cout << "Cell contains logical array: " << std::endl;
for (auto b : boolArr) {
printf_s("%d ", b);
}
std::cout << "\n";
}

void operator()(const TypedArray<double> doubleArr) {


std::cout << "Cell contains double array: " << std::endl;
for (auto elem : doubleArr) {
std::cout << elem << " ";
}
std::cout << "\n";
}

void operator()(const CharArray charArr) {


std::cout << "Cell contains char array: " << std::endl;
for (auto elem : charArr) {
std::cout << char(elem);
}
std::cout << "\n";
}

void operator()(const CellArray containedCellArray) {


DisplayCell(containedCellArray);
}
};

void DisplayCell(const CellArray cellArray) {


DisplayVisitor v;
for (auto elem : cellArray) {
apply_visitor(elem, v);
}
}

2-9
2 External Data Interface (EDI)

To use the class, pass a cell array to the DisplayCell function.

type callDisplayCell.cpp

int main() {
ArrayFactory factory;

// Create cell array


matlab::data::CellArray cellArray = factory.createCellArray({ 1,4 },
factory.createCharArray("A char array"),
factory.createArray<bool>({ 1,2 }, { false, true }),
factory.createArray<double>({ 2,2 }, { 1.2, 2.2, 3.2, 4.2 }),
factory.createCellArray({ 1,1 }, false));

// Call function
DisplayCell(cellArray);

return 0;
}

Visitor Class to Modify Contents of Cell Array


In this example, the CellModifyVisitor class implements the operations to modify the contents of
cell 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.

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>

using namespace matlab::data;


void ModifyCell(CellArray &cellArray);

class CellModifyVisitor {
public:
template <typename U>
void operator()(U arr) {}

void operator()(TypedArrayRef<bool> boolArrRef) {


std::cout << "Negate logical value: " << std::endl;
for (auto &b : boolArrRef) {
b = !b;
}
}

void operator()(TypedArrayRef<double> doubleArrRef) {


std::cout << "Add 1 to each value: " << std::endl;
for (auto &elem : doubleArrRef) {
elem = elem + 1;
}

2-10
Operate on C++ Arrays Using Visitor Pattern

std::cout << "\n";


}

void operator()(CharArrayRef charArrRef) {


std::cout << "Modify char array" << std::endl;
ArrayFactory factory;
charArrRef = factory.createCharArray("Modified char array");
}

void operator()(CellArrayRef containedCellArray) {


CellModifyVisitor v;
for (auto elem : containedCellArray) {
apply_visitor_ref(elem, v);
}
}

};

void ModifyCell(CellArray &cellArray) {


CellModifyVisitor v;
for (auto elem : cellArray) {
apply_visitor_ref(elem, v);
}
}

To use the class, pass a cell array to the ModifyCell function.

type callModifyCell.cpp

int main() {
ArrayFactory factory;

// Create cell array


matlab::data::CellArray cellArray = factory.createCellArray({ 1,4 },
factory.createCharArray("A char array"),
factory.createArray<bool>({ 1,2 }, { false, true }),
factory.createArray<double>({ 2,2 }, { 1.2, 2.2, 3.2, 4.2 }),
factory.createCellArray({ 1,1 }, false));

// 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)

MATLAB Data API Exceptions

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 API Types


In this section...
“matlab::data::ArrayDimensions” on page 2-16
“matlab::data::Enumeration” on page 2-16
“matlab::data::MATLABString” on page 2-16
“matlab::data::ObjectArray” on page 2-16
“matlab::data::String” on page 2-16
“matlab::data::Struct” on page 2-16
“buffer_ptr_t and buffer_deleter_t” on page 2-16
“iterator” on page 2-17
“const_iterator” on page 2-17
“reference” on page 2-17
“const_reference” on page 2-17
“Reference Types” on page 2-17

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.

buffer_ptr_t and buffer_deleter_t


buffer_ptr_t is defined as std::unique_ptr<T[], buffer_deleter_t>, where
buffer_deleter_t is defined as void (*)(void*).

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

Using Java Libraries from MATLAB


3 Using Java Libraries from MATLAB

Getting Started with Java Libraries


From MATLAB, you can:

• 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.

Platform Support for JVM Software


Every installation of MATLAB includes Java Virtual Machine (JVM™) software. To create and run
programs that access Java objects, use the Java interpreter via MATLAB commands.

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.

Learn More About Java Programming Language


For a complete description of the Java language and for guidance in object-oriented software design
and programming, consult outside resources. One resource is the help documentation on the
www.oracle.com website.

See Also

Related Examples
• “Call Java Method” on page 3-3

External Websites
• MATLAB Supported Language Interfaces

3-2
Call Java Method

Call Java Method


This example shows how to call a method of the java.util.ArrayList class. The example
demonstrates what it means to have Java objects as references in MATLAB.

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.

Choose Class Constructor to Create Java Object


Create an ArrayList object by using one of the class constructors. Display the class methods and
look for the ArrayList entries in the methods window.

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.

Shorten Class Name


Use the import function to refer to the ArrayList class without specifying the entire package name
java.util.

import java.util.ArrayList

Create Array List


Create an empty ArrayList object.

A = ArrayList;

Pass MATLAB Data to add Method


Add items to the ArrayList object. Look in the methods window at the signatures for the add
method.

void add (int,java.lang.Object)


boolean add (java.lang.Object)

Choose the boolean add(java.lang.Object) syntax. The argument java.lang.Object is a


Java type. To find the corresponding MATLAB type, look at the “Pass java.lang.Object” on page 3-48
table. If you pass a double argument, MATLAB converts it to a java.lang.Double type.

Add Elements to ArrayList


To call the add method, use MATLAB syntax.

3-3
3 Using Java Libraries from MATLAB

add(A,5);
A

A =

[5.0]

Alternatively, use Java syntax.


A.add(10);
A

A =

[5.0, 10.0]

Java Objects Are References in MATLAB


To observe the behavior of copying Java objects, assign A to a new variable B.
B = A;

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 =

[5.0, 10.0, 15.0]

Use ArrayList Object in MATLAB


Suppose that you call a Java method that returns a Java object of type ArrayList. If you invoked the
commands in the previous sections, variable A contains the following values:
class(A)

ans =

'java.util.ArrayList'

A =

[5.0, 10.0, 15.0]

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]

Convert the output to a MATLAB type.

res = cell(res)'

res =

1×3 cell array

[5] [10] [15]

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

Simplify Java Class Names Using import Function


MATLAB commands can refer to any Java class by its fully qualified name, which includes its package
name. For example, the following are fully qualified names:

• 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.

For example, suppose that a function contains these statements:

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.

str = String('hello'); % Create java.lang.String object


frm = Frame; % Create java.awt.Frame object
methods Enumeration % List java.util.Enumeration methods

To remove the list of imported Java classes, type:

clear import

See Also
import

Related Examples
• “Call Java Method” on page 3-3

3-6
Java Class Path

Java Class Path


To make Java classes available to MATLAB, place them on the Java class path. The class path is a
series of file and folder specifications. When loading a Java class, MATLAB searches the files and
folders in the order they occur on the class path. The search ends when MATLAB finds a file that
contains the class definition.

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.

• JAR File Classes


• Packages
• Individual (unpackaged) classes

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.

Java Class Path Options Action


Display class path Call the javaclasspath function.
Add files to static path Create an ASCII text file named javaclasspath.txt in
your preferences folder. For information and examples, see
“Static Path of Java Class Path” on page 3-9.
Add or remove files on dynamic path Call the javaclasspath, javaaddpath, or javarmpath
functions. These functions clear all existing variables and
global variables in the workspace. For more information,
see “Dynamic Path of Java Class Path” on page 3-15.
Augment search path for native method Create an ASCII text file named javalibrarypath.txt in
libraries. your preferences folder. For information, see “Locate Native
Method Libraries” on page 3-13.

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

• “Locate Native Method Libraries” on page 3-13

3-8
Static Path of Java Class Path

Static Path of Java Class Path


The static path is loaded at the start of each MATLAB session from the MATLAB built-in Java path and
the javaclasspath.txt file. The static path offers better Java class-loading performance than the
dynamic Java path. However, if you modify the static path, you must restart MATLAB.

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.

Create javaclasspath.txt File


Each line in the javaclasspath.txt file contains a reference to a Java class folder or JAR file. To
create the file:

1 Create an ASCII text file named javaclasspath.txt.


2 Enter the name of a Java class folder or JAR file, one per line. The format of the name depends on
how the class is defined.

• 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

Add Individual (Unpackaged) Classes


To make individual classes—classes that are not part of a package—available in MATLAB, specify the
full path to the folder containing the .class files. For example, for a compiled Java class in the file
c:\work\javaclasses\test.class, add the following entry to the javaclasspath.txt file.

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

Add JAR File Classes


A JAR file contains multiple Java classes and packages in a compressed ZIP format. For information
on the jar (Java Archive) tool and JAR files, consult your Java development documentation.

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).

• Edit the javaclasspath.txt file.

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

• “Dynamic Path of Java Class Path” on page 3-15


• “MATLAB Startup Folder”

External Websites
• Java™ Platform, Standard Edition 7 API Specification

3-11
3 Using Java Libraries from MATLAB

Load Java Class Definitions


MATLAB loads a Java class automatically when your code first uses it, for example, when you call its
constructor. To display a list of currently loaded Java classes, call the inmem function. This function
returns a list of classes in the output argument J. For example:

[~,~,j] = inmem;
j

j =

2×1 cell array

'java.util.Date'
'com.mathworks.ide.desktop.MLDesktop'

MATLAB displays what is loaded on your system.

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

Locate Native Method Libraries


Java classes can dynamically load native methods using the Java method
java.lang.System.loadLibrary("LibFile"). To load the library file LibFile, the folder
containing it must be on the Java Library Path. The JVM software defines this path at startup.

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.

• Create the 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

Load Class Using Java Class.forName Method


Instead of using the Java Class.forName method, call the MATLAB javaObjectEDT function. For
example, replace this statement:

java.lang.Class.forName('xyz.myapp.MyClass')

with:

javaObjectEDT('xyz.myapp.MyClass')

See Also
javaObjectEDT

3-14
Dynamic Path of Java Class Path

Dynamic Path of Java Class Path


MATLAB segments the Java class path into a static path and a dynamic path. MATLAB searches the
static path before the dynamic 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

Call Method in Your Own Java Class


To define new Java classes and subclasses of existing classes, use a Java Development Kit external to
MATLAB. For information on supported versions of JDK™ software, see the MATLAB Supported
Language Interfaces website.

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

How MATLAB Represents Java Arrays


The term Java array refers to a container object that holds a fixed number of values of a single type.
The type of an array is written as type[]. An array of arrays—also known as a multidimensional
array—uses two or more sets of brackets, such as String[][].

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).

For an example, see “Access Elements of Java Array” on page 3-21.

Shape of Java Arrays


A two-dimensional MATLAB array is a rectangle, as each row is of equal length and each column of
equal height. A Java array is an array of arrays and does not necessarily hold to this rectangular form.
Each individual lower-level array might have a different length.

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.

Interpret Size of Java Arrays


The MATLAB size function returns the length of the Java array. The number of columns is always 1.

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.

For example, consider this Java array.

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

Interpret Number of Dimensions of Java Arrays


The MATLAB ndims function always returns a value of 2 for the number of dimensions in a Java
array. This value is the number of dimensions in the top-level array.

Display Java Vector


MATLAB displays a Java vector as a column but processes it as if it were a row vector. For examples,
see “Concatenate Java Arrays” on page 3-28.

See Also
size | ndims

3-18
Create Array of Java Objects

Create Array of Java Objects


The MATLAB javaArray function lets you create a Java array that MATLAB handles as a single
multidimensional array. You specify the number and size of the array dimensions along with the class
of objects you intend to store in it. Using the one-dimensional Java array as its primary building block,
MATLAB then builds a Java array that satisfies the dimensions requested in the javaArray
command.

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[][]:

[0.7577] [0.7060] [0.8235] [0.4387] [0.4898]


[0.7431] [0.0318] [0.6948] [0.3816] [0.4456]
[0.3922] [0.2769] [0.3171] [0.7655] [0.6463]
[0.6555] [0.0462] [0.9502] [0.7952] [0.7094]

You must convert each element of A to the java.lang.Double type. For more information, see “Pass
Java Objects” on page 3-48.

Create Array of Primitive Java Types


To pass an array of a primitive Java type to a Java method, you must pass in an array of the equivalent
MATLAB type. For the type mapping details, see “MATLAB Type to Java Type Mapping” on page 3-
46.

For example, create a java.awt.Polygon by looking at the constructors in the following methods
window.

methodsview('java.awt.Polygon')

This constructor uses an array of Java int.

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

x = [10 40 95 125 10];


y = [50 15 0 60 50];
polygon = java.awt.Polygon(x,y,length(x));

To call the Polygon object method contains, look at its signature in the method window.

boolean contains (double,double)

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

Access Elements of Java Array


MATLAB Array Indexing
To access elements of a Java object array, use the MATLAB array indexing syntax, A(row,column).
In a Java program, the syntax is A[row-1][column-1].

Single Subscript Indexing


When you refer to the elements of a MATLAB matrix with a single subscript, MATLAB returns a single
element of the matrix. In contrast, single subscript (linear) indexing into a multidimensional Java
array returns a subarray.

For example, create a MATLAB 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

Copy the contents into a Java array.


javaArr = javaArray('java.lang.Integer',4,5);
for m = 1:4
for n = 1:5
javaArr(m,n) = java.lang.Integer(matlabArr(m,n));
end
end
javaArr

javaArr =

java.lang.Integer[][]:

[11] [12] [13] [14] [15]


[21] [22] [23] [24] [25]
[31] [32] [33] [34] [35]
[41] [42] [43] [44] [45]

Index value 3 returns a single element in the MATLAB array.


matlabArr(3)

ans = 31

Index value 3 returns the entire third row in a Java array.


javaArr(3)

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.

Colon Operator Indexing


To specify a range of elements in an array, use the colon operator (:). For example, create a 4-by-5
Java array.

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[][]:

[11] [12] [13] [14] [15]


[21] [22] [23] [24] [25]
[31] [32] [33] [34] [35]
[41] [42] [43] [44] [45]

Create a subarray row2Array from the elements in columns 2 through 4.

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]

Using END in a Subscript


To reference the top-level array in a multilevel Java array, use the end keyword as the first subscript.
For example, display data from the third to the last rows of Java array dblArray.

last2rows = dblArray(3:end,:)

last2rows =

java.lang.Double[][]:

[31] [32] [33] [34] [35]


[41] [42] [43] [44] [45]

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.

Converting Object Array Elements to MATLAB Types


When you access an element of a java.lang.Object array, MATLAB converts the element to a
MATLAB type, based on the table in “java.lang.Object Return Types” on page 3-51. MATLAB does
not convert elements of any other type of Java array.

For example, if a java.lang.Object array contains a java.lang.Double element, then MATLAB


converts the element to a MATLAB double. However, MATLAB does not convert a
java.lang.Double element in a java.lang.Double array. MATLAB returns it as
java.lang.Double.

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

Assign Values to Java Array


To assign values to objects in a Java object array, use the MATLAB command syntax. For example, the
following statement assigns a value to Java array A of type java.lang.Double.

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[][]:

[11] [12] [13] [14] [15]


[21] [22] [23] [24] [25]
[31] [32] [33] [34] [35]
[41] [42] [43] [44] [45]

Single Subscript Indexing Assignment


You can use single-subscript indexing to assign values to an array. For example, create a 5-by-1 Java
array and assign it to a row of dblArray.

onedimArray = javaArray('java.lang.Double',5);
for k = 1:5
onedimArray(k) = java.lang.Double(100*k);
end

Replace row 3 with the values of onedimArray.

dblArray(3) = onedimArray

dblArray =

java.lang.Double[][]:

[ 11] [ 12] [ 13] [ 14] [ 15]


[ 21] [ 22] [ 23] [ 24] [ 25]
[100] [200] [300] [400] [500]
[ 41] [ 42] [ 43] [ 44] [ 45]

3-25
3 Using Java Libraries from MATLAB

Linear Array Assignment


To assign a value to every element of a multidimensional Java array, use the MATLAB colon operator
(:). For example, initialize the contents of dblArray to zero.

dblArray(:) = java.lang.Double(0)

dblArray =

java.lang.Double[][]:

[0] [0] [0] [0] [0]


[0] [0] [0] [0] [0]
[0] [0] [0] [0] [0]
[0] [0] [0] [0] [0]

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[][]:

[125] [125] [125] [125] [125]


[250] [250] [250] [250] [250]
[375] [375] [375] [375] [375]
[500] [500] [500] [500] [500]

Empty Matrix Assignment


You can assign the empty matrix ([]) to a Java array element. MATLAB stores the null value, rather
than a 0-by-0 array.

dblArray(2,2) = []

dblArray =

java.lang.Double[][]:

[125] [125] [125] [125] [125]


[250] [] [250] [250] [250]
[375] [375] [375] [375] [375]
[500] [500] [500] [500] [500]

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.

For example, create a MATLAB array.

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[][]:

[125] [125] [125] [] [125]


[250] [] [250] [] [250]
[375] [375] [375] [] [375]
[500] [500] [500] [] [500]

3-27
3 Using Java Libraries from MATLAB

Concatenate Java Arrays


To concatenate arrays of Java objects, use the MATLAB cat function or the square bracket ([])
operators.

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.

Two-Dimensional Horizontal Concatenation


This example horizontally concatenates two Java arrays. Create 2-by-3 arrays d1 and d2.
d1 = javaArray('java.lang.Double',2,3);
for m = 1:2
for n = 1:3
d1(m,n) = java.lang.Double(n*2 + m-1);
end
end
d1

d1 =

java.lang.Double[][]:

[2] [4] [6]


[3] [5] [7]

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[][]:

[8] [10] [12]


[9] [11] [13]

Concatenate the two arrays along the second (horizontal) dimension.


d3 = cat(2,d1,d2)

d3 =

java.lang.Double[][]:

[2] [4] [6] [8] [10] [12]


[3] [5] [7] [9] [11] [13]

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[][]:

[1] [2] [3]


[4] [5] [6]

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[][]:

[]
[]
[]

Create a vector of length 3.

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

Create Java Array References


Java arrays in MATLAB are references. Assigning an array variable to another variable results in a
second reference to the array, not a copy of the array. For example, create and initialize origArray.

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[][]:

[11] [12] [13] [14]


[21] [22] [23] [24]
[31] [32] [33] [34]

Create a second reference to the array newArrayRef.

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[][]:

[11] [12] [13] [14]


[21] [22] [23] [24]
[ 0] [ 0] [ 0] [ 0]

See Also

Related Examples
• “Create Copy of Java Array” on page 3-32

3-31
3 Using Java Libraries from MATLAB

Create Copy of Java Array


To make a copy of an existing Java array, use subscript indexing. For example, create and initialize
origArray.

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[][]:

[11] [12] [13] [14]


[21] [22] [23] [24]
[31] [32] [33] [34]

Copy the entire contents to newArray.

newArray = origArray(:,:)

newArray =

java.lang.Double[][]:

[11] [12] [13] [14]


[21] [22] [23] [24]
[31] [32] [33] [34]

Change elements of newArray.

newArray(3,:) = java.lang.Double(0)

newArray =

java.lang.Double[][]:

[11] [12] [13] [14]


[21] [22] [23] [24]
[ 0] [ 0] [ 0] [ 0]

The values in origArray do not change.

origArray

origArray =

java.lang.Double[][]:

[11] [12] [13] [14]


[21] [22] [23] [24]
[31] [32] [33] [34]

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

Construct and Concatenate Java Objects

Create Java Object


Many Java method signatures contain Java object arguments. To create a Java object, call one of the
constructors of the class. For an example, see “Call Java Method” on page 3-3.

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.

Concatenate Objects of Same Class


To concatenate Java objects, use either the cat function or the [] operators.

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]

Concatenate Objects of Unlike Classes


If you concatenate objects of unlike classes, MATLAB finds one class from which all the input objects
inherit. MATLAB selects the lowest common parent in the Java class hierarchy as the output class.
For example, concatenating objects of java.lang.Byte, java.lang.Integer, and
java.lang.Double creates an object of the common parent to the three input classes,
java.lang.Number.

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]

If there is no common, lower-level parent, then the resultant class is java.lang.Object.

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

Save and Load Java Objects to MAT-Files


To save or serialize a Java object to a MAT-file, call the save function. To load the object from a MAT-
file back into MATLAB, call the load function.

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

Data Fields of Java Objects


Access Public and Private Data
Java classes can contain member variables called fields which might have public or private access.

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

Set the value of width.


frameDim.width = 42

frameDim =

java.awt.Dimension[width=42,height=0]

Display Public Data Fields of Java Object


To list the public fields of a Java object, call the fieldnames function. For example, create an
Integer object and display the field names.
value = java.lang.Integer(0);
fieldnames(value)

ans =
'MIN_VALUE'
'MAX_VALUE'
'TYPE'
'SIZE'

To display more information about the data fields, type:


fieldnames(value,'-full')

ans =
'static final int MIN_VALUE'

3-37
3 Using Java Libraries from MATLAB

'static final int MAX_VALUE'


'static final java.lang.Class TYPE'
'static final int SIZE'

Access Static Field Data


A static data field is a field that applies to an entire class of objects. To access static fields, use the
class name. For example, display the TYPE field of the Integer class.

thisType = java.lang.Integer.TYPE

thisType =

int

Alternatively, create an instance of the class.

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

Determine Class of Java Object


To find the class of a Java object, use the class function. For example:

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

Display Method Names


The methods function returns information on methods of MATLAB and Java classes.

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.

Display Method Signatures


With the '-full' qualifier, methods returns a listing of the method names (including inherited
methods) along with attributes, argument lists, and inheritance information on each. Each overloaded
method is listed separately.

For example, display a full description of all methods of the java.awt.Dimension object.

methods java.awt.Dimension -full

Methods for class java.awt.Dimension:


Dimension()
Dimension(java.awt.Dimension)
Dimension(int,int)
java.lang.Class getClass() % Inherited from java.lang.Object
int hashCode() % Inherited from java.lang.Object
boolean equals(java.lang.Object)
java.lang.String toString()
void notify() % Inherited from java.lang.Object
void notifyAll() % Inherited from java.lang.Object
void wait(long) throws java.lang.InterruptedException
% Inherited from java.lang.Object
void wait(long,int) throws java.lang.InterruptedException
% Inherited from java.lang.Object
void wait() throws java.lang.InterruptedException
% Inherited from java.lang.Object
java.awt.Dimension getSize()
void setSize(java.awt.Dimension)
void setSize(int,int)

Display Syntax in Figure Window


To see methods implemented by a particular Java (or MATLAB) class, use the methodsview function.
Specify the class name (along with its package name, for Java classes) in the command line. If you
have imported the package that defines this class, then the class name alone suffices.

This command lists information on all methods in the java.awt.MenuItem class:

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

Fields Displayed in methodsview Window

Field Name Description Examples


Name Method name addActionListener,
dispatchEvent
Return Type Type returned by the method void, java.lang.String
Arguments Types of arguments passed to boolean, java.lang.Object
method
Qualifiers Method type qualifiers abstract, synchronized
Other Other relevant information throws java.io.IOException
Inherited From Parent of the specified class java.awt.MenuComponent

See Also
methods | methodsview

3-41
3 Using Java Libraries from MATLAB

Determine What Classes Define a Method


To display the fully qualified name of a method implemented by a loaded Java class, call the which
function. To find all classes that define the specified method, use which with the -all qualifier.

For example, to find the package and class name for the concat method, type:

which concat

If the java.lang.String class is loaded, MATLAB displays:

concat is a Java method % java.lang.String method

If the String class has not been loaded, MATLAB displays:

concat not found.

Suppose that you loaded the Java String and java.awt.Frame classes. Both of these classes have
an equals method. Type:

which -all equals

The MATLAB display includes entries like these:

equals is a Java method % java.lang.String method


equals is a Java method % java.awt.Frame.equals
equals is a Java method % com.mathworks.jmi.MatlabPath method

The which function operates differently on Java classes than it does on MATLAB classes:

• which always displays MATLAB classes, whether they are loaded


• which only displays Java classes that are loaded

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

Java Methods That Affect MATLAB Commands


MATLAB commands that operate on Java objects and arrays use the methods that are implemented
within, or inherited by, the class. There are some MATLAB commands that you can alter in behavior
by changing the Java methods that they use.

Changing the Effect of disp and display


You call the disp function when you:

• Display the value of a variable or an expression in MATLAB.


• Terminate a command line without a semicolon.
• Display a Java object in MATLAB.

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.

Changing the Effect of isequal


The MATLAB isequal function compares two or more arrays for equality in type, size, and contents.
Also, you can use this function to test Java objects for equality.

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.

Changing the Effect of double, string, and char


You can change the output of the MATLAB double, string, and char functions by defining your
own Java methods, toDouble, toString, and toChar. For more information, see “Convert to
MATLAB Numeric Types” on page 3-52 and “Convert to MATLAB Strings” on page 3-53.

See Also

More About
• “Functions to Convert Java Objects to MATLAB Types” on page 3-52

3-43
3 Using Java Libraries from MATLAB

How MATLAB Handles Undefined Methods


If your MATLAB command invokes a nonexistent method on a Java object, MATLAB looks for a
function with the same name. If MATLAB finds a function of that name, it attempts to invoke it. If
MATLAB does not find a function with that name, it displays a message stating that it cannot find a
method by that name for the class.

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

Avoid Calling Java main Methods in MATLAB


When calling a main method from MATLAB, the method returns when it executes its last statement,
even if the method creates a thread that is still executing. In other environments, the main method
does not return until the thread completes execution.

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

Pass Data to Java Methods

MATLAB Type to Java Type Mapping


When you pass MATLAB data as arguments to Java methods, MATLAB converts the data into types
that best represent the data to the Java language. For information about type mapping when passing
data to arguments of type java.lang, see “Pass Java Objects” on page 3-48.

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.

MATLAB Java Parameter Type (Scalar or Array)


Argument Types Other Than Object

Closest Type <———————————————————————> Least Close Type


logical boolean byte short int long float double
double double float long int short byte boolean
single float double
uint8 byte short int long float double
int8
uint16 short int long float double
int16
uint32 int long float double
int32
uint64 long float double
int64
string String
scalar,
character
vector,
char scalar
string String[]
array,
cell array of
character
vectors
See “Pass
String
Arguments”
on page 3-
48.
Java object Java any
of type Object of superclass
jClass type of jClass
jClass

3-46
Pass Data to Java Methods

MATLAB Java Parameter Type (Scalar or Array)


Argument Types Other Than Object

Closest Type <———————————————————————> Least Close Type


cell array of Object[]
object
MATLAB Unsupporte
object d

How Array Dimensions Affect Conversion


The term dimension means the number of subscripts required to address the elements of an array.
For example, a 5-by-1 array has one dimension, because you index individual elements using one
array subscript.

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.

Convert Numbers to Integer Arguments


When passing an integer type to a Java method that takes a Java integer parameter, the MATLAB
conversion is the same as the Java conversion between integer types. In particular, if the integer is
out-of-range, it does not fit into the number of bits of the parameter type. For out-of-range integers,
MATLAB discards all lowest n bits. The value n is the number of bits in the parameter type. This
conversion is unlike the conversion between MATLAB integer types, where out-of-range integers are
converted to the maximum or minimum value represented by the destination type.

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:

• int, short, and byte parameter values to 0.


• long parameter values to java.lang.Long.MIN_VALUE.
• Inf and -Inf values to -1.
• NaN values to 0.

3-47
3 Using Java Libraries from MATLAB

Pass String Arguments


To call a Java method with an argument defined as java.lang.String, pass a MATLAB string or
character vector. MATLAB converts the argument to a Java String object. You also can pass a
String object returned by a Java method.

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 Objects


To call a method that has an argument belonging to a Java class (other than java.lang.Object),
you must pass a Java object that is an instance of that class. MATLAB does not support Java
autoboxing, the automatic conversion of MATLAB types to Java Object types. For example, MATLAB
does not convert double to java.lang.Double for a parameter of type Double.

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.

MATLAB Argument Java Object in Package java.lang


logical Boolean
double Double
single Float
char scalar Character
string scalar String
nonempty char vector
uint8 Byte
int8
uint16 Short
int16
uint32 Integer
int32
uint64 Long
int64
string array (nonscalar) String[]
cell array of character vectors
Java object Argument unchanged
cell array Object[]
MATLAB object Unsupported

3-48
Pass Data to Java Methods

Pass Array of Objects

To call a method with an argument defined as java.lang.Object or an array of


java.lang.Object, pass either a Java array or a MATLAB cell array. MATLAB automatically
converts the cell array elements to their Java types as described in the “Pass java.lang.Object” on
page 3-48 table. A Java array is an array returned from a Java constructor. You also can construct a
Java array in MATLAB using the javaArray function.

Pass Cell Array of Java Objects

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 =

1×2 cell array

[1×1 java.lang.Double] [1×1 java.lang.Float]

Pass Empty Matrices, Nulls, and Missing Values


MATLAB converts an empty matrix as follows.

• 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.

Empty (0-length) Java arrays remain unchanged.

MATLAB converts <missing> values in strings to 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.

When you call a Java method, MATLAB ensures that:


1 The object or class (for a static method) has a method by that name.
2 The invocation passes the same number of arguments of at least one method with that name.
3 Each passed argument is converted to the Java type defined for the method.

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

Handle Data Returned from Java Methods


If a Java method returns a primitive data type, then MATLAB converts the data, as shown in the table
in “Primitive Return Types” on page 3-51.

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.

Primitive Return Types


MATLAB converts primitive data returned from a Java method into types that best represent the data
to the MATLAB language. This table shows how MATLAB converts the data. For some Java types,
MATLAB treats scalar and array returns differently.

Java Return Type Resulting MATLAB Type — Resulting MATLAB Type —


Scalar Array
boolean logical logical
byte double int8
short double int16
int double int32
long double int64
float double single
double double double
char char char

Example

The signature for the java.lang.String method toCharArray is:

public char[] toCharArray()

Call the method on a String object. MATLAB converts the output to a char array.

str = java.lang.String('hello');
res = str.toCharArray'

res =

1×5 char array

hello

java.lang.Object Return Types


When a Java method is declared to return data of type java.lang.Object, MATLAB converts its
value depending on the actual type returned. This table shows how MATLAB converts the data.

3-51
3 Using Java Libraries from MATLAB

Actual Java Type Resulting MATLAB Type — Scalar


java.lang.Boolean logical
java.lang.Byte double
java.lang.Short double
java.lang.Integer double
java.lang.Long double
java.lang.Float double
java.lang.Double double
java.lang.Character char
java.lang.String char

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

Refer to the following signature for a getData method.

java.lang.Object getData()

If getData returns a java.lang.Integer object, then MATLAB converts the value to double.

Functions to Convert Java Objects to MATLAB Types


MATLAB only converts object data return values if the method signature specifies
java.lang.Object. If the signature specifies any other object type, then MATLAB does not convert
the value. For example, MATLAB does convert the return value for this method signature:

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:

• “Convert to MATLAB Numeric Types” on page 3-52


• “Convert to MATLAB Strings” on page 3-53
• “Convert to MATLAB Structure” on page 3-53
• “Convert to MATLAB Cell Array” on page 3-53

Convert to MATLAB Numeric Types

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.

Convert to MATLAB Strings

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.

Convert to MATLAB Structure

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 =

struct with fields:

npoints: 4
xpoints: [4×1 int32]
ypoints: [4×1 int32]

Convert to MATLAB Cell Array

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.*

% Create a Java array of double

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

% Create a Java array of points


ptArray = javaArray('java.awt.Point',3);
ptArray(1) = Point(7.1,22);
ptArray(2) = Point(5.2,35);
ptArray(3) = Point(3.1,49);

% Create a Java array of strings


strArray = javaArray('java.lang.String',2,2);
strArray(1,1) = String('one');
strArray(1,2) = String('two');
strArray(2,1) = String('three');
strArray(2,2) = String('four');

Convert each array to a cell array. You can use cellArray in MATLAB functions.

cellArray = {cell(dblArray),cell(ptArray),cell(strArray)}

cellArray =

1×3 cell array

{1×10 cell} {3×1 cell} {2×2 cell}

Each cell holds an array of a different type. Display the contents.

cellArray{1,1} % Array of type double


ans =

1×10 cell array

[7] [14] [21] [28] [35] [42] [49] [56] [63] [70]

cellArray{1,2} % Array of type Java.awt.Point

ans =

3×1 cell array

[1×1 java.awt.Point]
[1×1 java.awt.Point]
[1×1 java.awt.Point]

cellArray{1,3} % Array of type char array

ans =

2×2 cell array

'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

Java Heap Memory Preferences


You can adjust the amount of memory that MATLAB allocates for Java objects.

Note The default heap size is sufficient for most cases.

To adjust the Java heap size:

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

Java Methods With Optional Input Arguments


To call a Java method that accepts multiple optional input arguments, create a Java array in MATLAB.
For example, MyClass has a method with this signature:

public int myMethod(Integer... numbers)

To pass a scalar value 4 of type java.lang.Integer, create a variable numbers using javaArray.

numbers = javaArray('java.lang.Integer', 1);

Create oneNumber with value 4 and assign it to the Java array.

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

Call Back into MATLAB from Java


You can write Java applications that MATLAB users by connecting to MATLAB with the
“getCurrentMatlab” method in the com.mathworks.engine.MatlabEngine API. For information
about using this API, see “MATLAB Engine API for Java” on page 12-2.

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.*;

public class ExampleClass {


private MatlabEngine engine;

public double fevalExample() throws Exception {


engine = MatlabEngine.getCurrentMatlab();
double sqrtOut = engine.feval("sqrt", 4.0);
engine.close();
return sqrtOut;
}
}

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

Java Packages to Be Removed


Java packages and subpackages will not be available in MATLAB in a future release. To continue
using a Java package, install its JAR file and add the JAR file to the static path in MATLAB using the
instructions in “Static Path of Java Class Path” on page 3-9.

See Also

3-59
4

Read and Write MATLAB MAT-Files in C/C


++ and Fortran

• “Choosing Applications to Read and Write MATLAB MAT-Files” on page 4-2


• “Custom Applications to Access MAT-Files” on page 4-3
• “MAT-File API Library and Include Files” on page 4-5
• “What You Need to Build Custom Applications” on page 4-7
• “Copy External Data into MAT-File Format with Standalone Programs” on page 4-8
• “Create MAT-File in C or C++” on page 4-12
• “Read MAT-File in C/C++” on page 4-13
• “Create MAT-File in Fortran” on page 4-14
• “Read MAT-File in Fortran” on page 4-15
• “Work with mxArrays” on page 4-16
• “Table of MAT-File Source Code Files” on page 4-18
• “Build on macOS and Linux Operating Systems” on page 4-19
• “Build on Windows Operating Systems” on page 4-21
• “Share MAT-File Applications” on page 4-22
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran

Choosing Applications to Read and Write MATLAB MAT-Files


Under certain circumstances, you might need to write a custom program to interact with MATLAB
MAT-file data. These programs are called applications to read MAT-files. Before writing a custom
application to read MAT-file data, determine if MATLAB meets your data exchange needs by
reviewing the following topics.

• The save and load functions.


• “Supported File Formats for Import and Export”.
• The importdata function and “Import Images, Audio, and Video Interactively”.

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.

To write C/C++ applications, see:

• “MATLAB C API to Read MAT-File Data”


• “C Matrix API”
• C MEX API (optional)

To write Fortran applications, see:

• “MATLAB Fortran API to Read MAT-File Data”


• “Fortran Matrix API”
• “Fortran MEX API” (optional)

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

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

Why Write Custom Applications?


To bring data into a MATLAB application, see “Supported File Formats for Import and Export”. To
save data to a MAT-file, see “Save and Load Workspace Variables”. Use these procedures when you
program your entire application in MATLAB, or if you share data with other MATLAB users. There are
situations, however, when you must write a custom program to interact with data. For example:

• Your data has a custom format.


• You create applications for users who do not run MATLAB, and you want to provide them with
MATLAB data.
• You want to read data from an external application, but you do not have access to the source code.

Before writing a custom application, determine if MATLAB meets your data exchange needs by
reviewing the following topics.

• The save and load functions.


• “Supported File Formats for Import and Export”.
• The importdata function and “Import Images, Audio, and Video Interactively”.

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”.

MAT-File Interface Library


The MAT-File API contains routines for reading and writing MAT-files. Call these routines from your
own C/C++ and Fortran programs. Use these routines, rather than attempt to write your own code,
to perform these operations, since using the library insulates your applications from future changes
to the MAT-file structure. For more information, see “MAT-File API Library and Include Files” on page
4-5.

MATLAB provides the MATFile type for representing a MAT-file.

4-3
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran

MAT-File Routines

MAT-File API Function Purpose


matOpen Open a MAT-file.
matClose Close a MAT-file.
matGetDir Get a list of MATLAB arrays from a MAT-file.
matGetVariable Read a MATLAB array from a MAT-file.
matPutVariable Write a MATLAB array to a MAT-file.
matGetNextVariable Read the next MATLAB array from a MAT-file.
matDeleteVariable Remove a MATLAB array from a MAT-file.
matPutVariableAsGlobal Put a MATLAB array into a MAT-file such that the load
command places it into the global workspace.
matGetVariableInfo Load a MATLAB array header from a MAT-file (no data).
matGetNextVariableInfo Load the next MATLAB array header from a MAT-file (no
data).

MAT-File C-Only Routines

matGetFp Get an ANSI® C file pointer to a MAT-file.

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.

Exchanging Data Files Between Platforms


You can work with MATLAB software on different computer systems and send MATLAB applications
to users on other systems. MATLAB applications consist of MATLAB code containing functions and
scripts, and MAT-files containing binary data.

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

MAT-File API Library and Include Files


MATLAB provides include and library files to write programs to read and write MAT-files. The
following table lists the path names to these files. The term matlabroot refers to the root folder of
your MATLAB installation. The term arch is a unique string identifying the platform.

MAT-File API Folders

Platform Contents Folder


®
Microsoft Include files matlabroot\extern\include
Windows Libraries matlabroot\bin\win64
Examples matlabroot\extern\examples\eng_mat
macOS Include files matlabroot/extern/include
Linux Libraries matlabroot/bin/arch
Examples matlabroot/extern/examples/eng_mat

MAT-File API Include Files


The matlabroot\extern\include folder holds header files containing function declarations with
prototypes for the routines that you can access in the API Library. These files are the same for
Windows, macOS, and Linux systems. The folder contains:

• mat.h — Function prototypes for mat routines


• matrix.h — Definitions of the mxArray structure and function prototypes for matrix access
routines

MAT-File API Libraries


The name of the libraries folder, which contains the shared (dynamically linkable) libraries, is
platform-dependent.

Shared Libraries on Windows Systems

The bin folder contains the run-time version of the shared libraries:

• MAT-File library — matlabroot\extern\lib\win64\compiler\libmat.lib


• Matrix library — matlabroot\extern\lib\win64\compiler\libmx.lib
• MEX library (optional) — matlabroot\extern\lib\win64\compiler\libmex.lib

Shared Libraries on Linux Systems

The bin/arch folder, where arch is the value returned by the computer('arch') command,
contains the shared libraries.

• MAT-File library — matlabroot/bin/glnxa64/libmat.so


• Matrix library — matlabroot/bin/glnxa64/libmx.so
• MEX library (optional) — matlabroot/extern/bin/glnxa64/libmex.so

4-5
4 Read and Write MATLAB MAT-Files in C/C++ and Fortran

Shared Libraries on macOS Systems

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:

• MAT-File library — matlabroot/bin/maci64/libmat.dylib


• Matrix library — matlabroot/bin/maci64/libmx.dylib
• MEX library (optional) — matlabroot/extern/bin/maci64/libmex.dylib

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

What You Need to Build Custom Applications


To create a custom application, you need the tools and knowledge to modify and build source code. In
particular, you need a compiler supported by MATLAB.

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:

• MAT-File Interface Library


• Matrix Library

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

Copy External Data into MAT-File Format with Standalone


Programs
In this section...
“Overview of matimport.c Example” on page 4-8
“Declare Variables for External Data” on page 4-8
“Create mxArray Variables” on page 4-9
“Create MATLAB Variable Names” on page 4-9
“Read External Data into mxArray Data” on page 4-9
“Create and Open MAT-File” on page 4-10
“Write mxArray Data to File” on page 4-10
“Clean Up” on page 4-10
“Build the Application” on page 4-10
“Create the MAT-File” on page 4-10
“Import Data into MATLAB” on page 4-11

Overview of matimport.c Example


This topic shows how to create a standalone program, matimport, to copy data from an external
source into a MAT-file. The format of the data is custom, that is, it is not one of the file formats
supported by MATLAB.

The matimport.c example:

• Creates variables to read the external data.


• Copies the data into mxArray variables.
• Assigns a variable name to each mxArray. Use these variable names in the MATLAB workspace.
• Writes the mxArray variables and associated variable names to the MAT-file.

To use the data in MATLAB:

• Build the standalone program matimport.


• Run matimport to create the MAT-file matimport.mat.
• Open MATLAB.
• Use one of the techniques described in “Save and Load Workspace Variables”.

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.

Declare Variables for External Data


There are two external data values, a string and an array of type double. The following table shows
the relationship between the variables in this example.

4-8
Copy External Data into MAT-File Format with Standalone Programs

External Data Variable to Read mxArray Variable MATLAB Variable


External Data Name
Array of type double extData pVarNum inputArray
String extString pVarChar titleString

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 };

Create mxArray Variables


Functions in the MAT-File API use pointers of type mxArray to reference MATLAB data. These
statements declare pVarNum and pVarChar as pointers to an array of any size or type.
/*Pointer to the mxArray to read variable extData */
mxArray *pVarNum;
/*Pointer to the mxArray to read variable extString */
mxArray *pVarChar;

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);

Use the mxCreateString function to create an mxArray variable for extString.


pVarChar = mxCreateString(extString);

Create MATLAB Variable Names


matimport.c assigns variable names inputArray and titleString to the mxArray data. Use
these names in the MATLAB workspace. For more information, see “View Contents of MAT-File”.
const char *myDouble = "inputArray";
const char *myString = "titleString";

Read External Data into mxArray Data


Copy data from the external source into each mxArray.

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.

memcpy((void *)(mxGetPr(pVarNum)), (void *)extData, sizeof(extData));

The following statement initializes the pVarChar variable with the contents of extString.

pVarChar = mxCreateString(extString);

Variables pVarNum and pVarChar now contain the external data.

Create and Open MAT-File


The matOpen function creates a handle to a file of type MATFile. The following statements create a
file pointer pmat, name the file matimport.mat, and open it for writing.

MATFile *pmat;
const char *myFile = "matimport.mat";
pmat = matOpen(myFile, "w");

Write mxArray Data to File


The matPutVariable function writes the mxArray and variable name into the file.

status = matPutVariable(pmat, myDouble, pVarNum);


status = matPutVariable(pmat, myString, pVarChar);

Clean Up
To close the file:

matClose(pmat);

To free memory:

mxDestroyArray(pVarNum);
mxDestroyArray(pVarChar);

Build the Application


To build the application, use the mex function with the -client engine option.

copyfile(fullfile(matlabroot,'extern','examples','eng_mat',matimport.c'),'.','f')
mex -v -client engine matimport.c

Create the MAT-File


Run matimport to create the file matimport.mat. Either invoke the program from the system
command prompt, or at the MATLAB command prompt, type:

!matimport

4-10
Copy External Data into MAT-File Format with Standalone Programs

Import Data into MATLAB


Any user with a compatible version of MATLAB can read the matimport.mat file. Start MATLAB and
use the load command to import the data into the workspace.

load matimport.mat

To display the variables, type:

whos

Name Size Bytes Class

inputArray 3x3 72 double


titleString 1x43 86 char

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 or C++


In this section...
“Create MAT-File in C” on page 4-12
“Create MAT-File in C++” on page 4-12

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

Creating file mattest.mat...

To verify the MAT-file, at the MATLAB command prompt, type:

whos -file mattest.mat

Name Size Bytes Class

GlobalDouble 3x3 72 double array (global)


LocalDouble 3x3 72 double array
LocalString 1x43 86 char array

Grand total is 61 elements using 230 bytes

Create MAT-File in C++


The C++ version of matcreat.c is matcreat.cpp. Open the file in MATLAB Editor.

See Also

Related Examples
• “Table of MAT-File Source Code Files” on page 4-18

4-12
Read MAT-File in C/C++

Read MAT-File in C/C++


The matdgns.c example illustrates how to use the library routines to read and diagnose a MAT-file.
To see the code, open the file in MATLAB Editor.

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

Examining the header for each variable:


According to its header, array GlobalDouble has 2 dimensions
and was a global variable when saved
According to its header, array LocalString has 2 dimensions
and was a local variable when saved
According to its header, array LocalDouble has 2 dimensions
and was a local variable when saved

Reading in the actual array contents:


According to its contents, array GlobalDouble has 2 dimensions
and was a global variable when saved
According to its contents, array LocalString has 2 dimensions
and was a local variable when saved
According to its contents, array LocalDouble has 2 dimensions
and was a local variable when saved
Done

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

Create MAT-File in Fortran


The matdemo1.F example creates the MAT-file, matdemo.mat. To see the code, open the file in
MATLAB Editor.

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

Creating MAT-file matdemo.mat ...


Done creating MAT-file

To verify the MAT-file, at the MATLAB command prompt, type:

whos -file matdemo.mat

Name Size Bytes Class Attributes

Numeric 3x3 72 double


NumericGlobal 3x3 72 double global
String 1x33 66 char

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

Read MAT-File in Fortran


The matdemo2.F example illustrates how to use the library routines to read the MAT-file created by
matdemo1.F and describe its contents. To see the code, open the file in MATLAB Editor.

After building the program, view the results.

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

Work with mxArrays


In this section...
“Read Structures from a MAT-File” on page 4-16
“Read Cell Arrays from a MAT-File” on page 4-17

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.

Read Structures from a MAT-File


The matreadstructarray.c example is based on the analyze_structure function in
explore.c. For simplicity, this example only processes real elements of type double; refer to the
explore.c example for error checking and processing other types.

To see the code, open the file in the MATLAB Editor.

After building the program, run the application on the MAT-file, testpatient.mat.

First, create a structure patient and save it.

patient(1).name = 'John Doe';


patient(1).billing = 127.00;
patient(1).test = [79 75 73; 180 178 177.5; 172 170 169];
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68 70 68; 118 118 119; 172 170 169];

save testpatient.mat

Calculate the total of the billing field.

!matreadstruct testpatient.mat patient billing

Total for billing: 155.50

4-16
Work with mxArrays

Read Cell Arrays from a MAT-File


The matreadcellarray.c example is based on the analyze_cell function in explore.c.

To see the code, open the file in the MATLAB Editor.

After building the program, run the application on the MAT-file, testcells.mat.

First, create three cell variables and save.

cellvar = {'hello'; [2 3 4 6 8 9]; [2; 4; 5]};


structvar = {'cell with a structure'; patient; [2; 4; 5]};
multicellvar = {'cell with a cell'; cellvar; patient};

save testcells.mat cellvar structvar multicellvar

Display the mxArray type for the contents of cell cellvar.

!matreadcell testcells.mat cellvar

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

Table of MAT-File Source Code Files


The matlabroot/extern/examples/eng_mat folder contains C/C++ and Fortran source code for
examples demonstrating how to use the MAT-file routines. These examples create standalone
programs. The source code is the same for both Windows, macOS, and Linux systems.

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'))

where filename is the name of the source code file.

For build information, see:

• “MAT-File API Library and Include Files” on page 4-5


• “Build on macOS and Linux Operating Systems” on page 4-19
• “Build on Windows Operating Systems” on page 4-21

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.

For examples using the Matrix Library, see:

• “Tables of MEX Function Source Code Examples” on page 8-14.


• The explore.c example described in “Using Data Types” on page 7-9.

4-18
Build on macOS and Linux Operating Systems

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

Set Run-Time Library Path


At run time, you must tell the macOS and Linux operating system where the API shared libraries
reside by setting an environment variable. The macOS or Linux command you use and the values you
provide depend on your shell and system architecture. The following table lists the name of the
environment variable (envvar) and the value (pathspec) to assign to it. The term matlabroot
refers to the root folder of your MATLAB installation.

Operating System envvar pathspec


64-bit Apple Mac DYLD_LIBRARY_PATH matlabroot/bin/
maci64:matlabroot/sys/os/maci64
64-bit Linux LD_LIBRARY_PATH matlabroot/bin/
glnxa64:matlabroot/sys/os/glnxa64

Using the C Shell

Set the library path using the command.

setenv envvar pathspec

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

You can place these commands in a startup script, such as ~/.cshrc.

Using the Bourne Shell

Set the library path using the command.

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

You can place these commands in a startup script such as ~/.profile.

For more information, see Append library path to "DYLD_LIBRARY_PATH" in MAC.

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')

Use the following command to build it.

mex -client engine matcreat.c

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

Build on Windows Operating Systems


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. 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')

Use the following command to build it.

mex -client engine matcreat.c

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

Share MAT-File Applications


MATLAB requires shared library files for building a MAT-file application. You must also distribute the
run-time versions of these files along with any MAT-file application that you deploy to another system.
These libraries are in the matlabroot/bin/arch folder.

Library File Names by Operating System

Windows Linux Mac


libmat.dll libmat.so libmat.dylib
libmx.dll libmx.so libmx.dylib

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.

Library Dependency Commands

Windows Linux macOS


See the following instructions ldd -d libmat.so otool -L libmat.dylib
for Dependency Walker

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

Calling Functions in C++ Shared


Libraries from MATLAB

• “What Types of Files Define Your Library?” on page 5-3


• “Requirements for Building Interface to C++ Libraries” on page 5-4
• “Set Run-Time Library Path for C++ Interface” on page 5-6
• “Steps to Publish a MATLAB Interface to a C++ Library” on page 5-8
• “Header File and Import Library File on Windows” on page 5-10
• “Header and CPP Source Files” on page 5-11
• “Header File and Dynamic Shared Library File on macOS” on page 5-12
• “Call Functions in Windows Interface to C++ Shared Library” on page 5-13
• “Call Functions in Linux Interface to C++ Shared Library” on page 5-15
• “Header-Only HPP File” on page 5-17
• “Display Help for MATLAB Interface to C++ Library” on page 5-18
• “Publish Help Text for MATLAB Interface to C++ Library” on page 5-20
• “Define MATLAB Interface for C++ Library” on page 5-24
• “Define Missing SHAPE Parameter” on page 5-28
• “Define Missing MLTYPE Parameter” on page 5-35
• “Define Missing DIRECTION Parameter” on page 5-36
• “Build C++ Library Interface and Review Contents” on page 5-37
• “Sample C++ Library Definition File” on page 5-38
• “Call Functions in C++ Shared Library” on page 5-39
• “Limitations to C/C++ Support” on page 5-40
• “C++ Names That Are Invalid in MATLAB” on page 5-43
• “Troubleshooting C++ Library Definition Issues” on page 5-45
• “Troubleshooting MATLAB Interface to C++ Library Issues” on page 5-47
• “C++ to MATLAB Data Type Mapping” on page 5-49
• “MATLAB Object For C++ Arrays” on page 5-61
• “Handling Exceptions” on page 5-64
• “Errors Parsing Header Files on macOS” on page 5-65
• “Build Error Due to Compile-Time Checks” on page 5-66
• “Lifetime Management of C++ Objects in MATLAB” on page 5-67
• “Modify Library Help” on page 5-69
• “C++ Limitation Workaround Examples” on page 5-72
• “Use C++ Objects and Functions in parfor Loops” on page 5-80
• “Initialize Pointer Members of C++ Structures for MATLAB Interface to Library” on page 5-81
5 Calling Functions in C++ Shared Libraries from MATLAB

• “C++ Language Opaque Objects” on page 5-82


• “Define void* and void** Arguments” on page 5-83
• “Use Function Type Arguments” on page 5-89
• “Use Function and Member Function Templates” on page 5-91
• “Generate Interface” on page 5-93
• “Generate Interface on Windows” on page 5-94
• “Header File and Shared Object File on Linux” on page 5-95
• “Generate Interface on Linux” on page 5-96
• “Generate Interface on macOS” on page 5-97
• “Define Missing Constructs” on page 5-98
• “Define Missing Constructs” on page 5-100
• “Define Missing Constructs” on page 5-102
• “Define Missing Constructs” on page 5-104
• “Build Interface” on page 5-106
• “Build Interface” on page 5-108
• “Build Interface” on page 5-110
• “Build Interface to matrixoperations Library” on page 5-112
• “Call Library Functions on Windows” on page 5-114
• “Call Library Functions on Linux” on page 5-116
• “Call Library Functions on macOS” on page 5-118
• “Call matrixoperations Library Functions” on page 5-120
• “Generate Interface to school Library” on page 5-121
• “Define Missing Constructs in Interface to school Library” on page 5-122
• “Build Interface to school Library” on page 5-123
• “Call school Library Functions” on page 5-125

5-2
What Types of Files Define Your Library?

What Types of Files Define Your Library?


To build (publish) a MATLAB interface to a C++ library, you need:

• 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.

MATLAB does not support 32-bit libraries.


• On Windows — an import library .lib file. If the library is complied with a supported Microsoft
Visual Studio® compiler, then you need only the shared library .dll file.
• The C++ compiler that was used to build the C++ library.

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

Requirements for Building Interface to C++ Libraries


A shared library is a collection of classes and functions dynamically loaded by an application at run
time. The MATLAB interface to a C++ shared library supports libraries containing functionality
defined in C++ header and source files. You should be able to compile the headers in a C++
development environment and use the functionality in C++ applications.

Cpp Source and Header Files


To publish a MATLAB interface to a C++ library, identify specific functionality you want to include in
the interface and the associated header files containing that functionality.

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.

Shared Library Files


MATLAB supports 64-bit dynamic libraries on these platforms:

Platform Shared Library File Extension


Microsoft Windows Dynamic-link library file .dll
Import library file .lib
Linux Shared object file .so
Apple macOS Dynamic shared library file .dylib

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.

Note Not every C++ compiler supports every C++ feature.

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

Set Run-Time Library Path for C++ Interface


If the C++ library has a shared library file, then that file and its dependencies must be on your
system path or run-time search path (rpath). If the library is completely defined in header or source
files, then there might not be a shared library file. The publisher provides information about the
library files.

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.

Temporarily Set Run-Time Library Path in MATLAB on Windows


On Windows platforms, if the shared library files are located on rtPath, then in MATLAB call:

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.

Temporarily Set Run-Time Library Path at System Prompt


To set the run-time library path rtPath temporarily, run one of these commands before you start
MATLAB. You must restart MATLAB from this system prompt.

• Windows Command Processor:

set PATH=rtPath;%PATH%
• Linux C shell:

setenv LD_LIBRARY_PATH rtPath


• Linux Bourne 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

• macOS Bourne shell:

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

Steps to Publish a MATLAB Interface to a C++ Library


For examples to publish an interface, see:

• “Header File and Import Library File on Windows” on page 5-10


• “Header-Only HPP File” on page 5-17

• 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”.

For examples, see:

• “Header and CPP Source Files” on page 5-11


• “Header File and Import Library File on Windows” on page 5-10
• “Header File and Shared Object File on Linux” on page 5-95
• “Header-Only HPP File” on page 5-17

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

Header File and Import Library File on Windows


This example creates a MATLAB interface to a C++ library defined by matrixOperations.hpp for
Windows. MATLAB provides the library files in this folder:

fullfile(matlabroot, "extern", "examples", "cpp_interface")

Use these steps to create an interface to the matrixOperations library.

1 “Generate Interface on Windows” on page 5-94


2 “Define Missing Constructs” on page 5-98
3 “Build Interface” on page 5-110
4 “Call Library Functions on Windows” on page 5-114

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

Header and CPP Source Files


This example creates a MATLAB interface to a C++ library declared in the header file
matrixOperations.hpp and defined in the C++ source file matrixOperations.cpp.

MATLAB provides the source files in this folder:

fullfile(matlabroot,"extern","examples","cpp_interface");

Use these steps to create a matrixOperations interface for Windows.

1 “Generate Interface” on page 5-93


2 “Define Missing Constructs” on page 5-104
3 “Build Interface to matrixoperations Library” on page 5-112
4 “Call matrixoperations Library Functions” on page 5-120

See Also

Related Examples
• “Header-Only HPP File” on page 5-17

5-11
5 Calling Functions in C++ Shared Libraries from MATLAB

Header File and Dynamic Shared Library File on macOS


This example creates a MATLAB interface to a C++ library matrixOperations for macOS. The
library is defined by header file matrixOperations.hpp and dynamic shared library file
libmwmatrixOperations.dylib.

MATLAB provides these files in this folder:

fullfile(matlabroot,"extern","examples","cpp_interface");

Use these steps to create a matrixOperations interface for macOS.

1 “Generate Interface on macOS” on page 5-97


2 “Define Missing Constructs” on page 5-102
3 “Build Interface” on page 5-110
4 “Call Library Functions on macOS” on page 5-118

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

Call Functions in Windows Interface to C++ Shared Library


If you created the matrixOperations interface in the example “Header File and Import Library File
on Windows” on page 5-10, then you can use it in the following example. Navigate to the folder you
used to create the matrixOperations.dll interface file, for example :

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%

where rtPath is the output of:


rtPath = fullfile(matlabroot,'extern','examples','cpp_interface','win64','mingw64')

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.

To verify the updated system path, in MATLAB type:

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

To display the members of the package, type:

doc clib.matrixlib
Classes contained in clib.matrixlib:
Mat - clib.matrixlib.Mat Representation of C++ class Mat

Functions contained in clib.matrixlib:


addMat - clib.matrixlib.addMat Representation of C++ function addMat
updateMatByX - clib.matrixlib.updateMatByX Representation of C++ function updateMatByX
updateMatBySize - clib.matrixlib.updateMatBySize Representation of C++ function updateMatBySize

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

clib.matrixlib.updateMatByX Representation of C++ function updateMatByX


inputs
mat clib.matrixlib.Mat
X int32
outputs

clib.matrixlib.updateMatBySize Representation of C++ function updateMatBySize


inputs
mat clib.matrixlib.Mat
arr 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

Call Library Functions


Test the functions in the interface. For example, type:

matObj = clib.matrixlib.Mat; % Create a Mat object


intArr = [1,2,3,4,5];
matObj.setMat(intArr); % Set the values to intArr
retMat = matObj.getMat(5) % Display the values

retMat =

1×5 int32 row vector

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

Call Functions in Linux Interface to C++ Shared Library


If you created the matrixOperations interface in the example “Header File and Shared Object File
on Linux” on page 5-95, then you can use it in this example.

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:

setenv LD_LIBRARY_PATH rtPath


• Bourne 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.

To verify the updated system path, in MATLAB type:

syspath = split(getenv('PATH'),';')

Add the MATLAB interface file to the MATLAB 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

To display the members of the package, type:

doc clib.matrixlib
Classes contained in clib.matrixlib:
Mat - clib.matrixlib.Mat Representation of C++ class Mat

Functions contained in clib.matrixlib:


addMat - clib.matrixlib.addMat Representation of C++ function addMat
updateMatByX - clib.matrixlib.updateMatByX Representation of C++ function updateMatByX
updateMatBySize - clib.matrixlib.updateMatBySize Representation of C++ function updateMatBySize

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

clib.matrixlib.updateMatByX Representation of C++ function updateMatByX


inputs

5-15
5 Calling Functions in C++ Shared Libraries from MATLAB

mat clib.matrixlib.Mat
X int32
outputs

clib.matrixlib.updateMatBySize Representation of C++ function updateMatBySize


inputs
mat clib.matrixlib.Mat
arr 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

Call Library Functions


Test the functions in the interface. For example, type:

matObj = clib.matrixlib.Mat; % Create a Mat object


intArr = [1,2,3,4,5];
matObj.setMat(intArr); % Set the values to intArr
retMat = matObj.getMat(5) % Display the values

retMat =

1×5 int32 row vector

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

Header-Only HPP File


This example creates a MATLAB interface to a C++ library named school. The library is defined in
the header file school.hpp and does not have a shared library file. A library defined completely by
its header file is called a header-only library.

Library Artifacts MATLAB Package libname MATLAB Help


Header file school.hpp clib.school (default name) >> doc clib.school

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");

Use these steps to create a school interface for Windows.

1 “Generate Interface to school Library” on page 5-121


2 “Define Missing Constructs in Interface to school Library” on page 5-122
3 “Build Interface to school Library” on page 5-123
4 “Call school Library Functions” on page 5-125

See Also

Related Examples
• “Header and CPP Source Files” on page 5-11

5-17
5 Calling Functions in C++ Shared Libraries from MATLAB

Display Help for MATLAB Interface to C++ Library


Use these MATLAB functions to view information about the members of an interface:

• 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('.')

Display the classes and package functions.

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

Functions contained in clib.school:


getName - clib.school.getName Representation of C++ function getName

To display the inputs and outputs for the getName package function, click the getName link.

clib.school.getName Representation of C++ function getName


inputs
p clib.school.Person
outputs
RetVal string

To display class methods, call the methods function for each class. For example, type:

methods clib.school.Person

Methods for class clib.school.Person:

Person eq ge getAge getName gt le lt ne setAge setName

Methods of clib.school.Person inherited from handle.

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

Name Return Type Arguments


Person clib.school.Person obj (clib.school.Person input1)
Person clib.school.Person obj (name, uint64 scalar age)
Person clib.school.Person obj

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

Publish Help Text for MATLAB Interface to C++ Library


When you publish an interface, the clibgen.generateLibraryDefinition function inserts C++
header file comments and other default text about classes and functions. The doc function displays
this text to the user. You can disable inserting C++ comments or modify the text by editing the library
definition file.

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.

Automatically Use C++ Comments for Help Text


If these public constructs contain C++ comments, then MATLAB appends the comments to the
default MATLAB descriptions.

• Functions and arguments


• Member functions and arguments
• Classes and structs
• Data members
• Enumerations and enumerants

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

The Description, DetailedDescription, and EnumerantDescriptions arguments take string


values. You can manually update the text in these values on page 5-21. For example, there might be
more content in the .hpp file than MATLAB includes by default. Or you might want to include code
examples for your use case.

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.

Manually Update Help Text


This example uses the interface built in “Header-Only HPP File” on page 5-17. For another examples,
see “Modify Library Help” on page 5-69.

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

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 modify this text, edit defineschool.mlx. Search for the text Representation of C++ class
Person.

Modify the "Description" value. Change:

"clib.school.Person Representation of C++ class Person."

to:

"clib.school.Person Class defined by name and age."

Save the file.

To rebuild the library, restart MATLAB. Navigate to the folder containing defineschool.mlx. Delete
the existing interface file.

delete school\*.dll

Build the interface and update the path.

build(defineschool)
addpath school

Display the updated help.

doc clib.school

Classes contained in clib.school:


Person - clib.school.Person Class defined by name and age
Teacher - clib.school.Teacher Representation of C++ class Teacher
Student - clib.school.Student Representation of C++ class Student

5-21
5 Calling Functions in C++ Shared Libraries from MATLAB

Compare Generated Help With Header File Comments


The example described in “Modify Library Help” on page 5-69 shows generated 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.

MATLAB uses C++ comments in the PlatformUtils.hpp file.


/** @name Initialization and Panic methods */
//@{

/** Perform per-process parser initialization


*
* Initialization <b>must</b> be called first in any client code.
*
* @param locale The locale to use for messages.
*
* The locale is set if the Initialize() is invoked for the very first time,
* to ensure that each and every message loader, in the process space, share
* the same locale.
*
* All subsequent invocations of Initialize(), with a different locale, have
* no effect on the message loaders, either instantiated, or to be instantiated.
*
* To set to a different locale, client application needs to Terminate() (or
* multiple Terminate() in the case where multiple Initialize() have been invoked
* before), followed by Initialize(new_locale).
*
* The default locale is "en_US".
*
* @param nlsHome User specified location where MsgLoader retrieves error message files.
* the discussion above with regard to locale, applies to nlsHome as well.
*
* @param 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().
*
* @param 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()
*/
static void Initialize(const char* const locale = XMLUni::fgXercescDefaultLocale
, const char* const nlsHome = 0
, PanicHandler* const panicHandler = 0
, MemoryManager* const memoryManager = 0);

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

This content is from the external library documentation.

Initialization <b>must</b> be called first in any client code.

Inputs
locale read-only string
locale The locale to use for messages.

nlsHome read-only string


nlsHome User specified location where MsgLoader retrieves error message files.
the discussion above with regard to locale, applies to nlsHome as well.

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

Define MATLAB Interface for C++ Library

How to Complete Definitions in Library Definition File


The MATLAB interface converts C++ function signatures into MATLAB function signatures. Some C+
+ language constructs do not have unique matches in the MATLAB language. MATLAB uses a library
definition file (with the MLX file extension), which a publisher creates and modifies to provide missing
information. The publisher must have enough C++ language skills to interpret a function signature
and provide the missing information.

MATLAB informs you about these incomplete definitions through this


clibgen.generateLibraryDefinition warning message:
Warning: Some C++ language constructs in the files for generating interface file
are not supported and not imported.

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.

After creating the library definition file definelibName.mlx using


clibgen.generateLibraryDefinition, you might have to modify the contents to include
functionality in the interface. Use the Live Editor to modify the MLX definition file. Replace the
<DIRECTION>, <SHAPE>, and <MLTYPE> parameters with the missing information. These parameters
are used for these cases.

• 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:

• Uncomment the code defining the function.


• Delete the parameter name, including the <> characters.
• Pause to allow the code suggestions to be displayed.
• If the suggestions do not appear, make sure that the definelibName.mlx file is on your MATLAB
path.

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.

Reconcile MATLAB Signature Conflicts


After generating and editing a library definition file, there might be two or more functions or other
constructs with identical MATLAB signatures. To check for this conflict, validate the definition file.
For example, for the definition file definelibname, type:

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:

• Revise the defineArgument or defineOutput arguments to create a unique MATLAB signature.


The conflict occurs when there are multiple overloaded functions, and you specify the same
argument parameters. See “How to Complete Definitions in Library Definition File” on page 5-24.
• Remove one of the functions by commenting out the definition of the construct. The conflict might
occur when you use one of the clibgen.generateLibraryDefinition name-value arguments
to convert all cases of a particular type. You also can remove an overloaded function.

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.

Customize Function Template Names


Review the unique function names generated from function templates in the library definition file. For
example, class A in this header file defines a function template show and provides instantiations for
types int, double, and const A.

class A{}; // User type


template<typename T> void show(T a) {}
template void show<int>(int);

5-25
5 Calling Functions in C++ Shared Libraries from MATLAB

template void show<double>(double);


template<> void show<const A &>(const A& a){}

If you build an interface A to this library, MATLAB creates overloaded functions that have signatures
for these instantiations.
summary(defineA)

MATLAB Interface to libname Library

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);

% By default 'AddTrailingSingletons' is false


defineArgument(setImagesFunctionDefinition, "images", "uint8", "input", ...
["numOfImages", "height", "width"])

void setColorImage(const uint8_t * image, int height, int width, int colorDepth);

defineArgument(setColorImageFunctionDefinition, "image", "uint8", "input", ...


["height", "width", "colorDepth"], "AddTrailingSingletons", true)

In MATLAB, create an image array such that:

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

Define Missing SHAPE Parameter


In C++, pointer arguments are used for both scalar data and array data. To use a pointer as an array,
MATLAB needs dimension information to safely convert the array between C++ and MATLAB. The
SHAPE parameter helps you specify the dimensions for the pointer.

Note These pointer types can only be used as scalars. Define SHAPE as 1 in the MLX file.

• Pointers representing arrays of C++ class objects


• Pointers to non-const primitive arrays returned from a function

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.

Define Pointer Argument to Fixed Scalar


C++ Signature and Role defineArgument Values
of Pointer
The input to this function is For argument in, set SHAPE to 1.
a scalar pointer in.
defineArgument(readScalarPtrDefinition, "in", ...
void readScalarPtr(int const *
"int32",
in) "input", 1);
The input to this function is For argument in, set SHAPE to 1.
a scalar pointer to class
ns::MyClass2. defineArgument(readScalarPtrDefinition, "in", ...
"clib.cppUseCases.ns.MyClass2", "input", 1);
void readScalarPtr(ns::MyClass2 const * in)

Define Pointer Argument


C++ Signature defineArgument Values
The input to this function is For argument mat, set SHAPE to argument m.
a pointer to an integer array
of length m. defineArgument(readMatrix1DPtrDefinition, "mat", ...
"int32", "input", "m");
void readMatrix1DPtr(int const * mat,
size_t m)
The input to this function is For argument mat, set SHAPE to a fixed integer, such as 5.
a pointer to a fixed-length
array mat. defineArgument(readMatrix1DPtrFixedSizeDefinition, ...
"mat", "int32", "input", 5);
void readMatrix1DPtrFixedSize(int const * mat)

5-28
Define Missing SHAPE Parameter

C++ Signature defineArgument Values


The input to this function is For argument mat, set SHAPE to ["m","n"].
a pointer to a two-
dimensional integer matrix defineArgument(readMatrix2DPtrDefinition, "mat", ...
"int32", "input", ["m","n"]);
mat of size m-by-n.

void readMatrix2DPtr(int const * mat,


size_t m, size_t n)
The input to this function is For argument mat, set SHAPE to a fixed integer, such as 6.
a pointer to a two-
dimensional matrix mat of defineArgument(readMatrix2DPtrFixedSizeDefinition, ...
"mat", "int32", "input", 6);
fixed dimensions.

void readMatrix2DPtrFixedSize(int const * mat)


The input to this function is For argument mat, set SHAPE to ["m","n","p"].
a pointer to a three-
dimensional matrix mat of defineArgument(readMatrix3DPtrDefinition, "mat", ...
"int32", "input", ["m","n","p"]);
size m-by-n-by-p.

void readMatrix3DPtr(int const * mat,


size_t m, size_t n, size_t p)

Define Array Argument


C++ Signature defineArgument Values
The input to this function is For argument mat, set SHAPE to length len.
a one-dimensional array mat
of length len. defineArgument(readMatrix1DArrDefinition, "mat", ...
"int32", "input", "len");
void readMatrix1DArr(int const [] mat,
size_t len)

Define Output Pointer Argument


C++ Signature defineArgument Values
The input to this function is For the return value RetVal, set SHAPE to argument len.
a pointer to an array of
length len. The function defineOutput(getRandomValuesDefinition, "RetVal", ...
"int32", "len");
returns a pointer argument
as output.

int const * getRandomValues(size_t len)


The output argument of this For the return value RetVal, set SHAPE to an integer, such as 5.
function is a pointer to a
fixed-length array. defineOutput(getRandomValuesFixedSizeDefinition, ...
"RetVal", "int32", 5);
int const * getRandomValuesFixedSize()

5-29
5 Calling Functions in C++ Shared Libraries from MATLAB

Define Scalar Object Argument


C++ Signature defineArgument Values
The input to this function is For the myc2 argument, set SHAPE to 1.
a pointer to class
ns::MyClass2. defineArgument(addClassByPtrDefinition, "myc2", ...
"clib.cppUseCases.ns.MyClass2", "input", 1);
double addClassByPtr(ns::MyClass2 const * myc2)
The input to this function is For argument myc2, set SHAPE to 1.
a pointer to class
ns::MyClass2. defineArgument(updateClassByPtrDefinition, "myc2", ...
"clib.cppUseCases.ns.MyClass2", "input", 1);
void updateClassByPtr(ns::MyClass2 * myc2,
double a, short b, long c)
The input to this function is For argument myc2, set SHAPE to 1.
a pointer to class
ns::MyClass2. defineArgument(readClassByPtrDefinition, "myc2", ...
"clib.cppUseCases.ns.MyClass2", "input", 1);
void readClassByPtr(ns::MyClass2 * myc2)
The input to this function is For argument myc2, set SHAPE to 1.
a pointer to class
ns::MyClass2. defineArgument(fillClassByPtrDefinition, "myc2", ...
"clib.cppUseCases.ns.MyClass2", "input", 1);
void fillClassByPtr(ns::MyClass2 * myc2,
double a, short b, long c)

Define Matrix Argument


C++ Signature defineArgument Values
The input to this function is For argument mat, set DIRECTION to "inputoutput" and SHAPE to
a pointer to an integer "len".
vector of length len. The
argument x modifies the defineArgument(updateMatrix1DPtrByXDefinition, ...
"mat", "int32", "inputoutput", "len");
input argument.

void updateMatrix1DPtrByX(int * mat,


size_t len, int x)
The input to this function is For argument mat, set DIRECTION to "inputoutput" and SHAPE to
a reference to an integer "len".
array of length len.
Argument x modifies input defineArgument(updateMatrix1DArrByXDefinition, ...
"mat", "int32", "inputoutput", "len");
argument mat.

void updateMatrix1DArrByX(int [] mat,


size_t len, int x)

5-30
Define Missing SHAPE Parameter

C++ Signature defineArgument Values


The input to this function is For argument mat, set DIRECTION to "input" and SHAPE to "len".
a pointer to an integer
vector of length len. The defineArgument(addValuesByPtrDefinition, "mat", ...
"int32", "input", "len");
function does not modify the
input argument.

int addValuesByPtr(int * mat,


size_t len)
The input to this function is For argument mat, set DIRECTION to "input" and SHAPE to "len".
a reference to an integer defineArgument(addValuesByArrDefinition, ...
array of length len. The "mat", "int32", "input", "len");

function does not modify the


input argument.

int addValuesByArr(int [] mat,


size_t len)
This function creates an For argument mat, set DIRECTION to "output" and SHAPE to "len".
integer vector of length len
and returns a reference to defineArgument(fillRandomValuesToPtrDefinition, ...
"mat", "int32", "output", "len");
the vector.

void fillRandomValuesToPtr(int * mat,


size_t len)
This function creates an For argument mat, set DIRECTION to "output" and SHAPE to "len".
integer vector of length len
and returns a reference to defineArgument(fillRandomValuesToArrDefinition, ...
"mat", "int32", "output", "len");
the vector.

void fillRandomValuesToArr(int [] mat,


size_t len)

Define String Argument


C++ Signature defineArgument Values
The input to this function is a C-style string. For argument str, set MLTYPE to "string"
and SHAPE to "nullTerminated".
char const * getStringCopy(char const * str)
defineArgument(getStringCopyDefinition, "str", ...
"string", "input", "nullTerminated");
The return value for this function is a string. For return value RetVal, set MLTYPE to
"string" and SHAPE to "nullTerminated".
char const * getStringCopy(char const * str)
defineOutput(getStringCopyDefinition, "RetVal", "str
"nullTerminated");

5-31
5 Calling Functions in C++ Shared Libraries from MATLAB

C++ Signature defineArgument Values


The return value for this function is a string of MATLAB defines argument pmsg as an input
length buf. variable of type clib.array.libname.Char.

void getMessage(char * pmsg, int buf) %defineArgument(getMessageDefinition, "pmsg", ...


"clib.array.libname.Char", "input", <SHAPE>);

To define pmsg as an output variable of type


string:

• Replace "input" with "output".


• Replace the type with "string" and set
<SHAPE> to "nullTerminated".
• Add the "NumElementsInBuffer" name-
value argument set to variable buf.

defineArgument(getMessageDefinition, "pmsg", ...


"string, "output", "nullTerminated", ...
"NumElementsInBuffer", "buf");
The input to this function is a string specified by For argument chArray, set MLTYPE to "char"
length len. and SHAPE to "len".

void readCharArray(char const * chArray, defineArgument(readCharArrayDefinition, "chArray", .


size_t len) "char", "input", "len");
The input to this function is an array of type int8 For argument int8Array, set MLTYPE to
and length len. "int8" and SHAPE to "len".

void readInt8Array(char const * int8Array, defineArgument(readInt8ArrayDefinition, "int8Array",


size_t len) "int8", "input", "len");
The return value for this function is a scalar of For return value RetVal, set MLTYPE to
characters. "char" and SHAPE to 1.

char const * getRandomCharScalar() defineOutput(getRandomCharScalarDefinition, ...


"RetVal", "char", 1);
The type of the return value for this function is For return value RetVal, set MLTYPE to
int8. "int8" and SHAPE to 1.
defineOutput(getRandomInt8ScalarDefinition, ...
char const * getRandomInt8Scalar() "RetVal", "int8", 1);

This function updates the input argument chArray. For argument chArray, set DIRECTION to
The length of chArray is len. "inputoutput" and SHAPE to "len".

void updateCharArray(char* chArray, defineArgument(updateCharArrayDefinition, ...


size_t len) "chArray", "int8", "inputoutput", "len");
The input to these functions is an array of C-string For argument strs, set SHAPE to the array
of size numStrs. ["numStrs", "nullTerminated"].

void readCStrArray(char** strs, int numStrs);defineArgument(readCStrArrayDefinition, ...


"strs", "string", "input", ["numStrs", "nullTerm
void readCStrArray(char* strs[], int numStrs);

5-32
Define Missing SHAPE Parameter

C++ Signature defineArgument Values


The input to these functions is a const array of C-
Call clibgen.generateLibraryDefinition
string of size numStrs. with TreatConstCharPointerAsCString set
to true to automatically define SHAPE for
void readConstCStrArray (const char** strs, int numStrs);
argument strs as ["numStrs",
"nullTerminated"].
void readConstCStrArray (const char* strs[], int numStrs);
defineArgument(readConstCStrArrayDefinition, ...
"strs", "string", "input", ["numStrs", "nullTerm
The input to this function is a fixed-size array of C- For argument strs, set SHAPE to the array [5,
string. "nullTerminated"].

void readFixedCStrArray (char* strs[5]); defineArgument(readFixedCStrArrayDefinition, ...


"strs", "string", "input", [5, "nullTerminated"]
The input to this function is a fixed-size const array Call clibgen.generateLibraryDefinition
of C-string. with TreatConstCharPointerAsCString set
to true to define SHAPE for argument strs as
void readConstCFixedStrArray (const char* strs[5]); [5, "nullTerminated"].

defineArgument(readConstFixedCStrArrayDefinition, ..
"strs", "string", "input", [5, "nullTerminated"]

Define Typed Pointer Argument


C++ Signature defineArgument Values
The input to this function is For argument input1, set DIRECTION to input and SHAPE to 1.
a pointer to typedef
intDataPtr. defineArgument(useTypedefPtrDefinition, "input1", ...
"int16", "input", 1);
void useTypedefPtr(intDataPtr input1)

intDataPtr is defined as:

typedef int16_t intData;


typedef intData * intDataPtr;

Use Property or Method as SHAPE


You can use a public nonstatic C++ data member (property) as the SHAPE for the return type of a
nonstatic method or another nonstatic data member (property) in the same class. The property must
be defined as an integer (C++ type int). Similarly, you can use a static C++ data members as a
SHAPE parameter for a return type of a static method or another static data member in the same
class.

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

C++ Signature SHAPE Values


The size of data member For property rowData, set SHAPE to an array of rows, cols, and
rowData is defined by data channels.
members rows and cols addProperty(ADefinition, "rowdata", ["rows","cols","channels"]...
and by the result of method "Description", "clib.array.libname.Int Data member of C++ class A.");

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

Define Missing MLTYPE Parameter


MATLAB automatically converts C++ types to MATLAB types, as described in “C++ to MATLAB Data
Type Mapping” on page 5-49.

If the C++ type for the argument is a string, then use these options to choose values for the MLTYPE
and SHAPE arguments.

C++ Type MATLABT DIRECTI Options for SHAPE


ype ON
char*a "int8" "input" Scalar value
Array of scalar values
char** "string "input" vector
char*[] "
const char* "char" Scalar value
Array of scalar values
"string "input" "nullTerminated"
"
const char** "char" "input" Scalar value
const Array of scalar values
char*[] "string "input" "nullTerminated"
"
a. These types are equivalent to MATLAB char:

• 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

Define Missing DIRECTION Parameter


In C++, pointer arguments can be used to pass and return data from a function. Use the DIRECTION
parameter to specify if the argument is read-only input, output only, or a modifiable input argument.

The DIRECTION parameter has one of these values:

• "input"—Input argument only

If a pointer argument is used to pass data to the function, then it must appear as an input
argument in the MATLAB signature.

The DIRECTION value for C-string parameters must be input.


• "output"—Output argument only

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.

void passData(double *data);

Assuming data is a scalar double value, this table shows the MATLAB signature based on its role.

C++ Role for data MATLAB Signature


Input data only to passData % Set DIRECTION = "input"
passData(data)
Return data only from passData % Set DIRECTION = "output"
[data] = passData()
Input and output data for % Set DIRECTION = "inputoutput"
passData [data] = passData(data)

5-36
Build C++ Library Interface and Review Contents

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 From Library Definition File


If you created a MLX library definition file by using the clibgen.generateLibraryDefinition
function, then use the build function. For example, for library definition file definelibName, type:

build(definelibName)
addpath libName

Display the functionality in the library.

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

Review Contents of Interface


MATLAB automatically copies some C++ comments, if available, from the header and source files
into the interface. You can modify or replace this content. For more information, see “Publish Help
Text for MATLAB Interface to C++ Library” on page 5-20.

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

Sample C++ Library Definition File


This example shows a library definition file created from a C++ header file.

Example Header File

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"))

Library Definition File definecppUseCases.mlx

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:

double addClassByPtr(ns::MyClass2 const * myc2)

Argument myc2 is not defined for MATLAB. See this statement, which contains <SHAPE>:

defineArgument(addClassByPtrDefinition, "myc2",
"clib.cppUseCases.ns.MyClass2", "input", <SHAPE>);

To define the argument, replace <SHAPE> with 1:

defineArgument(addClassByPtrDefinition, "myc2",
"clib.cppUseCases.ns.MyClass2", "input", 1);

Uncomment the seven lines defining the function and save the MLX file.

To find the other undefined functions, search for:

%validate

5-38
Call Functions in C++ Shared Library

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.

retVal = clib.libname.funcname(arg1, arg2, ...)

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

Limitations to C/C++ Support


You can create a MATLAB interface to 64-bit shared libraries based on C++98 and commonly
occurring C++11 features. However, if a library contains the following data types or language
features, then the functionality is not included in the MATLAB interface to the library. You might be
able to include this functionality by creating a wrapper header file. For more information, see “C++
Limitation Workaround Examples” on page 5-72.

Data Types Not Supported


• 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:

• MATLAB supports char** types.


• MATLAB supports ** pointers to custom classes used as function or method parameter types.
• MATLAB supports void** used as function or method parameter types.
• Multilevel pointers, such as type***
• C function pointers and std::function as function return types or data members. You also
cannot pass a MATLAB function as input to C function pointers or std::function parameter.
• Class templates with incomplete or no instantiations
• union
• Types defined in the std namespace, except these supported types:

• std::string
• std::wstring
• std::u16string
• std::u32string
• std::vector
• std::shared_ptr
• std::function

Messages About Unsupported Types

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.

To view these messages, use the 'Verbose' option in the clibgen.generateLibraryDefinition


or clibgen.buildInterface functions.

5-40
Limitations to C/C++ Support

Language Features Not Supported


• move constructor
• Overloaded operator functions
• Unnamed namespaces and classes
• Preprocessor directives (macros)
• Global variables
• Variadic functions
• Function templates with incomplete or no instantiations
• Creating objects of classes in std namespace, including custom classes.
• Smart pointer semantics. Only std::shared_ptr is supported. MATLAB does not support
operator overloads, move semantics, and the member functions in the class definition of the smart
pointer which might restrict their effectiveness. Instead, a std::shared_ptr<T> behaves as
type T in MATLAB. Type T can be passed as input for std::shared_ptr<T>, and type T is
received as output for std::shared_ptr<T>.
• Namespace aliases. Use original namespace name instead.

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.

Note Saving C++ objects into a MAT-file is not supported.

Inheriting C++ class in MATLAB


MATLAB does not support creating MATLAB classes that inherit a C++ interface class.

Unsupported Class Methods


MATLAB does not support implementing operators by defining these associated functions.

Operation Method to Define


a < b lt(a,b)
a > b gt(a,b)
a <= b le(a,b)
a >= b ge(a,b)
a ~= b ne(a,b)
a == b eq(a,b)
a(s1,s2,...,sn) subsref(a,s)
a(s1,...,sn) = b subsassign(a,s,b)
b(a) subsindex(a)

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

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

Use Invalid Property Names


You might need to access a property in MATLAB, but the name of the property might not be a valid
MATLAB name. For example, the name might begin with an underscore. To derive this name at run
time, use this MATLAB syntax, where propertyName is a string scalar or character vector that, when
evaluated, returns an instance of a property.

clib.libName.className.(propertyName)

For example, suppose that you have interface clib.demo.MyClass with this property:
class MyClass
{
public:
int _mean;
};

To assign property _mean to a variable, type:

x = clib.demo.MyClass;
xmean = x.('_mean')

This syntax is valid for names less than the maximum identifier length namelengthmax.

Use Invalid Enumerated Value Names


You might need to create an enumerated value in MATLAB, but the name of that value might not be a
valid MATLAB name. For example, the enumerant name might begin with an underscore. To derive a
value from this name at run time, use this MATLAB syntax, where enumMember is a string scalar or
character vector that, when evaluated, returns an instance of an enumeration.

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:

Description: "clib.enums.keywords Representation of C++ enumeration"


DefiningLibrary: [1×1 clibgen.LibraryDefinition]
CPPName: "keywords"
MATLABType: "int32"
Valid: 1
MATLABName: "clib.enums.keywords"
Entries: ["_for" "_while" "_class" "_enums" "_template" "_typename"]

To assign entry _class to a variable, type:

var = clib.enums.keywords.('_class');

This syntax is valid for names less than the maximum identifier length namelengthmax.

Certain Class Names with typedef Aliases Not Supported


MATLAB does not support a class typedef alias name with the same name as a method in the class.

5-44
Troubleshooting C++ Library Definition Issues

Troubleshooting C++ Library Definition Issues

MATLAB Did Not Create MLX Definition File


Sometimes, the content of library files exceeds limits, which causes MATLAB to create only an M file
but not an MLX file. Search your output folder for a definition file of the form definelibName.m and
edit the contents as you do the MLX version.

Cannot Open or Too Slow to Load MLX Definition File


If you have performance issues opening the MLX file, then you can use the corresponding
definelibName.m file instead. First delete the MLX file, and then open the .m file in MATLAB Editor.

Shape Value Not Found


When you use an argument to define the shape for another argument, you must define the argument
in the C++ function signature. In the example “Generated Library Definition MLX File” on page 5-
45, suppose that you define the shape of argument in as argument inb:
defineArgument(taskDefinition, "in", "clib.array.libname.Int", "input", "inb");

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.

Invalid Shape Value Type


When you use an argument to define the shape for another argument, you must consider the types for
both arguments. In the example “Generated Library Definition MLX File” on page 5-45, suppose that
you define argument inc as a null-terminated string:
defineArgument(taskDefinition, "inc", "string", "input", "nullTerminated");

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.

Why Is a Function or a Type Missing from the Definition File?


If a library contains any unsupported language features or data types on page 5-40, then the
functionality is not included in the library definition file.

Generated Library Definition MLX File


For information about the error messages, refer to this example. The C++ signature is:

void task(int * in, double * ind, int sz, char const * inc)

5-45
5 Calling Functions in C++ Shared Libraries from MATLAB

%taskDefinition = addFunction(libDef, ...


% "void task(int * in,double * ind,int sz,char const * inc)", ...
% "MATLABName", "clib.libname.task", ...
% "Description", "clib.libname.task Representation of C++ function task.");
% Modify help description values as needed.
%defineArgument(taskDefinition, "in", "clib.array.libname.Int", "input", <SHAPE>);
% <MLTYPE> can be "clib.array.libname.Int",or "int32"
%defineArgument(taskDefinition, "ind", "clib.array.libname.Double", "input", <SHAPE>);
% <MLTYPE> can be "clib.array.libname.Double", or "double"
%defineArgument(taskDefinition, "sz", "int32");
%defineArgument(taskDefinition, "inc", <MLTYPE>, "input", <SHAPE>);
% <MLTYPE> can be "clib.array.libname.Char","int8","string", or "char"
%validate(taskDefinition);

Build Error undefined reference or unresolved external symbol


When you build an interface by using the clibgen.generateLibraryDefinition or
clibgen.buildInterface functions, the compiler might display error messages about an
undefined reference or an unresolved external symbol. These errors often occur when you
forget to provide information about shared library files. To include shared library files, use the
'Libraries' name-value argument.

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

Troubleshooting MATLAB Interface to C++ Library Issues


Library Interface Does Not Exist Or Is Not Loaded
MATLAB searches 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.

Library Interface Does Not Contain Any Instances Of Type


To see what classes are available, see the documentation for your library. For library libname, type:
doc clib.libname

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.

Invalid clib Array Element Type Name


The MATLAB name for a clib array element type includes clib and the library name. For more
information, see clibArray.

For example, for library libname containing class MyClass, the clib array type is:
clib.array.libname.MyClass

and the MATLAB element type is:


clib.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

and the MATLAB element type is:


clib.libname.Double

First Letter Of Type Must Be Capitalized


When creating a clib array, MATLAB converts the names of fundamental C++ types to upper camel
case.

For example, if the C++ type is signed int, then the MATLAB clib array type for library libname
is:
clib.array.libname.SignedInt

and the element type is:


clib.libname.SignedInt

5-47
5 Calling Functions in C++ Shared Libraries from MATLAB

For strings, if the C++ type is std::string, then:

clib.array.libname.std.String % clib array type


clib.libname.std.String % element type

Access Violation When Calling Library Function


The library file must be built in release mode, using 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.

5-48
C++ to MATLAB Data Type Mapping

C++ to MATLAB Data Type Mapping


These tables show how MATLAB converts C/C++ data into equivalent MATLAB data types. MATLAB
uses these mappings when creating library definition files. Use this information to help you define
missing information on page 5-24 for MATLAB signatures.

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.

For these types, specify DIRECTION as "input" and SHAPE as 1.

C Fixed-Width Integer Type Equivalent MATLAB Type


int8_t int8
uint8_t uint8
int16_t int16
uint16_t uint16
int32_t int32
uint32_t uint32
int64_t int64
uint64_t uint64

Non-Fixed-Width Integer Types

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

std::vector<T> Integer Types

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.

C++ std::vector<T> Integer Equivalent MATLAB Element Type


Type clib.array Type for libname
std::vector<int8_t> clib.array.libname.Signe clib.libname.SignedChar
dChar
std::vector<uint8_t> clib.array.libname.Unsig clib.libname.UnsignedCha
nedChar r
std::vector<int16_t> clib.array.libname.Short clib.libname.Short 

std::vector<uint16_t> clib.array.libname.Unsig clib.libname.UnsignedSho
nedShort  rt 
std::vector<int32_t> clib.array.libname.Int clib.libname.Int
std::vector<uint32_t> clib.array.libname.Unsig clib.libname.UnsignedInt
nedInt
std::vector<int64_t> clib.array.libname.LongL clib.libname.LongLong 
ong 
std::vector<uint64_t> clib.array.libname.Unsig clib.libname.UnsignedLon
nedLongLong  gLong 

Floating Point Types

For these types, specify DIRECTION as "input" and SHAPE as 1.

C Floating Point Type Equivalent MATLAB Type


float single
double double

C++ std::vector<T> Equivalent MATLAB Element Typea


Floating Point Type clib.array Type for libname
std::vector<float> clib.array.libname.Singl clib.libname.Single
e
std::vector<double> clib.array.libname.Doubl clib.libname.Double
e
a. For information about using element types, see “MATLAB Object For C++ Arrays” on page 5-61.

5-50
C++ to MATLAB Data Type Mapping

String and Character Types


These tables show how C++ string and char data types correspond to MATLAB data types. The
data mapping depends on how the type is used in the function, as a parameter, return type, or data
member (property). For example, these function definitions show different uses of type T.

void fnc(T); // T is a parameter type (MATLAB input argument)


T fnc(); // T is a return type (MATLAB output argument)

Plain C++ Character and String Types

For these types, specify DIRECTION as "input" and SHAPE as 1.

Plain C++ Character Type Equivalent MATLAB Type


char int8
signed char int8
unsigned char uint8
wchar_t char
char16_t char
char32_t char

Plain C++ String Type Equivalent MATLAB Type


std::string string
(MATLAB converts characters to the platform
default encoding for std::string.)
std::wstring string
std::u16string string
std::u32string string

C++ char* and char[] Types

C++ Parameter Type MLTYPE SHAPE


a
char* "int8" Scalar value
const char* "char" Array of scalar values
"clib.array.lib.Char"
"string" "nullTerminated"
char[] "int8" Scalar value
const char[] "char"
"clib.array.lib.Char"
"string" "nullTerminated"
wchar_t* and const "char" Scalar value
wchar_t* Array of scalar values
wchar_t[] and const
wchar_t[]
char16_t* and const
char16_t*

5-51
5 Calling Functions in C++ Shared Libraries from MATLAB

C++ Parameter Type MLTYPE SHAPE


char16_t[] and const "string" "nullTerminated"
char16_t[]
char32_t* and const
char32_t*
char32_t[] and const
char32_t[]
a. MATLAB sets the DIRECTION of char* parameter types to "input". To define a char* argument as a string output, set
DIRECTION to "output" and use the 'NumElementsInBuffer' name-value argument. For an example, see the
getMessage function in the “Define String Argument” on page 5-31 table.

C++ Return Type MLTYPE SHAPE


char* "int8" 1
wchar_t*
char16_t*
char32_t*
const char* "int8" any dimension
const wchar_t* "char"
const char16_t* "clib.array.lib.Char"
const char32_t* "string" "nullTerminated"

C++ Data Member Type Equivalent MATLAB Type


char* string
char[] clib.array.lib.Char
int8
char
wchar_t* string
char16_t* char
char32_t*

5-52
C++ to MATLAB Data Type Mapping

C++ Array of Strings

C++ Array of String MLTYPE SHAPEa


Parameter Type
char** "string" {scalar
const char** value,"nullTerminated"}
char*[] {parameter
const char*[] name,"nullTerminated"}
wchar_t**
const wchar_t**
wchar_t*[]
const wchar_t*[]
char16_t**
const char16_t**
char16_t*[]
const char16_t*[]
char32_t**
const char32_t**
char32_t*[]
const char32_t*[]
a. 1D array of string. The first element is the size of array and the last element is the shape of each element.

C++ Array of String Data Member Type Equivalent MATLAB Type


char*[] and const char*[] string
wchar_t*[] and const wchar_t*[]
char16_t*[] and const char16_t*[]
char32_t*[] and const char32_t*[]

MATLAB does not support these const and nonconst C++ return types.

• char** and char*[]


• wchar_t** and wchar_t*[]
• char16_t** and char16_t*[]
• char32_t** and char32_t*[]

std::vector<T> String Types

For these types, specify DIRECTION as "input".

C++ std::vector<T> String Equivalent MATLAB Element Typea


Type clib.array Type for libname
std::vector<std::string> clib.array.libname.std.S clib.libname.std.String 
tring 
std::vector<std::wstring clib.array.libname.std.w clib.libname.std.wString
> String   
std::vector<std::u16stri clib.array.libname.std.u clib.libname.std.u16Stri
ng> 16String  ng 

5-53
5 Calling Functions in C++ Shared Libraries from MATLAB

C++ std::vector<T> String Equivalent MATLAB Element Typea


Type clib.array Type for libname
std::vector<std::u32stri clib.array.libname.std.u clib.libname.std.u32Stri
ng> 32String  ng 
a. For information about using element types, see “MATLAB Object For C++ Arrays” on page 5-61.

bool Types
For these types, specify DIRECTION as "input" and SHAPE as 1.

bool Type Equivalent MATLAB Type


bool logical

std::vector<T> bool Type Equivalent MATLAB Element Typea


clib.array Type for libname
bool clib.array.libname.Bool clib.libname.Bool
a. For information about using element types, see “MATLAB Object For C++ Arrays” on page 5-61.

Static Data Members


MATLAB treats public static and public const static data members as read-only properties. You cannot
update the value of a static data member. For example, build an interface lib to this header file.

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 = clib.lib.Set.p1 + clib.lib.Set.p2

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 the variable before calling any commands in clib.lib.

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.

C++ Parameter Type Equivalent MATLAB DIRECTION SHAPE


Type in libname
T clib.libname.T "input" 1
T* clib.libname.T "input" 1
clib.array.libname "input" 1
.T Fixed dimensions: Enter
a numerical array, such
as [5,2].
Variable dimensions:
Enter a string array of
parameter names, such
as ["row","col"].
T[] clib.array.libname "input" 1
.T Fixed dimensions
Variable dimensions
T& clib.libname.T "input" 1
T** clib.libname.T "output" 1
std::vector<T> clib.array.libname "input" 1
.T
std::shared_ptr<T> clib.libname.T "input" 1
std::shared_ptr<T> clib.array.libname "input" 1
& .T "inputoutput"

This table shows how to configure a C++ return type T.

C++ Return Type Equivalent MATLAB Type in SHAPE


libname
T clib.libname.T 1
T* clib.libname.T 1
clib.array.libname.T 1
Fixed dimensions: Enter a
numerical array, such as [5,2].
Variable dimensions: Enter a
string array of parameter
names, such as
["row","col"].

5-55
5 Calling Functions in C++ Shared Libraries from MATLAB

C++ Return Type Equivalent MATLAB Type in SHAPE


libname
T[] clib.array.libname.T 1
Fixed dimensions
Variable dimensions
T& clib.libname.T 1
std::vector<T> clib.array.libname.T 1
std::shared_ptr<T> clib.libname.T 1
std::shared_ptr<T>& clib.array.libname.T 1

This table shows how to configure a C++ data member type T.

C++ Data Member Type Equivalent MATLAB Type in SHAPE


libname
T clib.libname.T 1
T* clib.libname.T 1
clib.array.libname.T 1
Fixed dimensions: Enter a
numerical array, such as [5,2].
Variable dimensions: Enter a
string array of parameter
names, such as
["row","col"].
T[] clib.array.libname.T 1
Fixed dimensions
Variable dimensions
std::shared_ptr<T> clib.libname.T 1

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.

C++ Parameter Type Equivalent MATLAB DIRECTION SHAPE


Type in libname
T clib.libname.T "input" 1

C++ Return Type Equivalent MATLAB Type in SHAPE


libname
T clib.libname.T 1

C++ Data Member Type Equivalent MATLAB Type in SHAPE


libname
T clib.libname.T 1

5-56
C++ to MATLAB Data Type Mapping

nullptr Argument Types


nullptr Input Argument Types

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 clib.type.nullptr type is supported for these MATLAB argument types:

• scalar object pointers


• clib arrays

nullptr Return Types

The C++ interface returns type-specific empty values for functions that return nullptr.

• For type double, MATLAB returns [] for the value double.empty.


• For all other fundamental types, MATLAB returns an MLTYPE.empty value. To determine MLTYPE,
look for the C or C++ type in the tables in this topic. MLTYPE is in the Equivalent MATLAB Type
column.

To test for nullptr types, call the isempty function.


• For non-fundamental types, MATLAB returns a nullptr object. To test for nullptr objects, call
the clibIsNull function.

void* Argument Types


To pass void* arguments to and from C++ functions, see “Define void* and void** Arguments” on
page 5-83. MATLAB does not support void* data members.

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

Fundamental Types Mapping

C++ Type Equivalent MATLAB void* Type


int8_t* int8
uint8_t* uint8
int16_t* int16
uint16_t* uint16
int32_t* int32
uint32_t* uint32
int64_t* int64
uint64_t* uint64
float* single
double* double
bool* logical

clib.array Types Mapping


a
C++ Type Equivalent MATLAB clib.array for
libname
char* clib.array.libname.Char
signed char* clib.array.libname.SignedChar
unsigned char* clib.array.libname.UnsignedChar
short* clib.array.libname.Short 
unsigned short* clib.array.libname.UnsignedShort 
int* clib.array.libname.Int
unsigned int* clib.array.libname.UnsignedInt
long* clib.array.libname.Long
unsigned long* clib.array.libname.UnsignedLong
long long* clib.array.libname.LongLong 
unsigned long long* clib.array.libname.UnsignedLongLong 
float* clib.array.libname.Float
double* clib.array.libname.Double
bool* clib.array.libname.Bool
a. MATLAB converts the names of fundamental C++ types to upper camel case.

Type

typedef void* Mapping

C++ Type Equivalent MATLAB Type for libname


typedef void* Handle clib.libname.Handle

5-58
C++ to MATLAB Data Type Mapping

Unsupported Data Types


If the data type of an argument/return type in a class constructor, method, or function is one of these
types, or if the library contains any unsupported language features on page 5-40, then the
functionality is not included in the MATLAB interface to the library.

• 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:

• MATLAB supports char** types.


• MATLAB supports ** pointers to custom classes used as function or method parameter types.
• MATLAB supports void** used as function or method parameter types.
• Multilevel pointers, such as type***
• C function pointers and std::function as function return types or data members. You also
cannot pass a MATLAB function as input to C function pointers or std::function parameter.
• Class templates with incomplete or no instantiations
• union
• Types defined in the std namespace, except these supported types:

• std::string
• std::wstring
• std::u16string
• std::u32string
• std::vector
• std::shared_ptr
• std::function

Messages About Unsupported Types

MATLAB reports on constructs that use unsupported types. To view these messages, use the
'Verbose' option in the clibgen.generateLibraryDefinition or clibgen.buildInterface
functions.

For example, suppose that functionName in ClassName is defined in HeaderFile.h. If an


argument to functionName is of unsupported type type, then MATLAB does not add
functionName to the definition file. In addition, if 'Verbose' is true, then
clibgen.generateLibraryDefinition displays this message.
Did not add member 'functionName' to class 'ClassName' at HeaderFile.h:290.
'type' is not a supported type.

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

MATLAB Object For C++ Arrays


MATLAB provides an interface, clib.array, which wraps C++ native arrays and std::vector
types. The term clib array refers to the MATLAB representation of these C++ types.

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.

Create MATLAB Array of C++ Objects


To create a MATLAB object that represents C++ native arrays or std::vector types, call the
MATLAB clibArray function. For example, suppose that your library libname defines a class
myclass. In MATLAB, you refer to this class as clib.libname.myclass. To create an array of five
myclass objects, use this syntax:

myclassArray = clibArray('clib.libname.myclass',5);

The type of the MATLAB array myclassArray is clib.array.libname.myclass. To access an


element of myclassArray, use MATLAB indexing. For example, to access the first element, use this
syntax:

e = myclassArray(1)

The element type is clib.libname.myclass.

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.

To create an array of five elements for a user-defined class, type:

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 Saving C++ objects into a MAT-file is not supported.

Note You cannot create an array of C++ objects using square brackets.

5-61
5 Calling Functions in C++ Shared Libraries from MATLAB

Convert MATLAB Array to C++ Array Object


You can use an existing MATLAB array as a C++ array object. Call the clibConvertArray function.

MATLAB C++ Object Array Properties


MATLAB arrays created with clibArray or clibConvertArray have these properties.

Property Type Access Description


Dimensions double read-only C++ dimensions of the array
vector
Resizable logical read-only • true—add/remove element allowed
scalar • false—add/remove element not allowed

MATLAB C++ Object Array Methods


MATLAB arrays created with clibArray or clibConvertArray have these methods.

Method Signature Description


append append([elemen Add an optionally specified element to the end of the
t]) array.

For a primitive MATLAB clib array, if there is no input


argument, then a zero value is appended.

For a class-type MATLAB clib array, if there is no input


argument, then the class-type default constructor is
appended. If the class-type default constructor is
deleted, a runtime error occurs.
removeLast removeLast Remove the last element of the array. If the MATLAB clib
array is empty, a runtime error occurs.
double double Convert to double precision.
int8 int8 Convert to int8.
uint8 uint8 Convert to uint8.
int16 int16 Convert to int16.
uint16 uint16 Convert to uint16.
int32 int32 Convert to int32.
uint32 uint32 Convert to uint32.
int64 int64 Convert to int64.
uint64 uint64 Convert to uint64.
logical logical Convert numeric values to logical.

5-62
MATLAB Object For C++ Arrays

Treat C++ Native Arrays of Fundamental Type as MATLAB Fundamental


Types
By default, MATLAB represents C++ native arrays of fundamental types with the MATLAB
clib.array types. If you need to preserve fundamental MATLAB array types with outputs, then
build your interface with the ReturnCArrays argument set to false. For more information, see
clibgen.generateLibraryDefinition.

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

Errors Parsing Header Files on macOS


The clibgen.generateLibraryDefinition and clibgen.buildInterface functions fail when
parsing some header files on the macOS platform.

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

Header file simple2.hpp includes simple1.hpp.

#include "simple1.hpp"

// class definitions based on simple1.hpp content


// other functionality

This call to clibgen.generateLibraryDefinition generates errors parsing the header file on


macOS.
clibgen.generateLibraryDefinition(["simple1.hpp","simple2.hpp"],"PackageName","simple")

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

// Start of simple2.hpp content. Do not add the include simple1.hpp statement.

// class definitions based on simple1.hpp content


// other functionality

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

Build Error Due to Compile-Time Checks


Compile-time assertions in a C++ shared library, such as static_assert, are not supported, but a
construct with the assertion might be instantiated. To avoid an error when building a MATLAB
interface to the library, comment out the lines in the definition file that define the construct before
building the interface.

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

Lifetime Management of C++ Objects in MATLAB


If a library creates an object, then the library is responsible for releasing the memory. Likewise, if
MATLAB creates the object, then MATLAB is responsible for releasing the memory. There are
situations, however, where memory allocated by both the user library and MATLAB might be
combined into a single MATLAB object. MATLAB lets you control the lifetime management of objects
by specifying 'ReleaseOnCall' and 'DeleteFcn' arguments in the library definition file.

Pass Ownership of Memory to the Library


MATLAB owns memory that is allocated by calling a constructor. The user library should not free this
memory. To change this behavior, set the 'ReleaseOnCall' argument in defineArgument
(ConstructorDefinition), defineArgument (FunctionDefinition), or defineArgument
(MethodDefinition).

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>);

Set DIRECTION and SHAPE and add a 'ReleaseOnCall' argument.


defineArgument(setInputObjDefinition,'obj','clib.libname.ObjClass','input',1,'ReleaseOnCall',true);

Pass Ownership of Memory to MATLAB


MATLAB does not free memory allocated by the library. You can transfer ownership of memory to
MATLAB by using the 'DeleteFcn' name-value argument for these arguments:

• 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.

Manage Memory of Returned Pointer or Reference

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.

ObjClass *objCreate(int32 a, int32 b);


void objFree(ObjClass *obj);

To use objFree when MATLAB deletes object ObjClass, modify the objCreate definition in the
library definition file.
%defineOutput(objCreateDefinition,'RetVal','clib.libname.ObjClass',<SHAPE>);

Set SHAPE and add a 'DeleteFcn' argument.


defineOutput(objCreateDefinition,'RetVal','clib.libname.ObjClass',1,'DeleteFcn','libname::objFree');

The MATLAB delete function calls libname::objFree.

myObj = clib.libname.objCreate(x,y)
delete(myObj);

Manage Memory of Double Pointer Input Argument

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);

Add the 'DeleteFcn' argument.


defineArgument(createTaskDefinition, "taskHandle", "clib.lib.handle", "output", 1, "DeleteFcn", "clearTask");

See Also
defineArgument (FunctionDefinition) | defineArgument (MethodDefinition) |
defineOutput (MethodDefinition) | defineOutput (FunctionDefinition)

5-68
Modify Library Help

Modify Library Help


This example shows how to modify help generated for a MATLAB interface to a C++ library.

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.

mex -setup cpp


• Identify the path myPath to your .hpp and shared library files. This example uses the library file
xerces-c_3.lib.
includePath = "myPath\include";
libFile = "myPath\lib\xerces-c_3.lib";

• 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";

Define MATLAB Interface


For information about defining the interface, see “Define MATLAB Interface for C++ Library” on
page 5-24.

• Generate the library definition file defineMyXercesLibrary.mlx.


clibgen.generateLibraryDefinition(headers,...
"IncludePath",includePath,...
'Libraries',libFile,...
"Verbose",true,...
"PackageName","MyXercesLibrary")

• Edit the defineMyXercesLibrary.mlx file. This example resolves undefined functionality for
the Initialize method only. Search for:

C++ Signature: static void xercesc_3_1::XMLPlatformUtils::Initialize


• Update the defineArgument statements for locale and nlsHome to be null-terminated strings
by replacing <MLTYPE> with "string" and <SHAPE> with "nullTerminated". For information
about updating the code, see “Define Missing SHAPE Parameter” on page 5-28.
defineArgument(InitializeDefinition, "locale", "string", "input", "nullTerminated", "Description", "locale The locale to use for mes
defineArgument(InitializeDefinition, "nlsHome", "string", "input", "nullTerminated", "Description", "nlsHome User specified location

• 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

defineArgument(InitializeDefinition, "panicHandler", "clib.MyXercesLibrary.xercesc_3_1.PanicHa


defineArgument(InitializeDefinition, "memoryManager", "clib.MyXercesLibrary.xercesc_3_1.Memory
• Validate the library definition file and resolve any errors.

libDef = defineMyXercesLibrary

Update Generated Help Text


• Review the auto-generated help text.
className = "xercesc_3_1::XMLPlatformUtils";
methodName = "Initialize";
for i = 1:numel(libDef.Classes)
if (matches(libDef.Classes(i).CPPName,className))
classID = i;
for j = 1:numel(libDef.Classes(i).Methods)
if (startsWith(libDef.Classes(i).Methods(j).MATLABSignature,methodName))
methodID = j;
end
end
end
end
Description = libDef.Classes(classID).Methods(methodID).Description
DetailedDescription = libDef.Classes(classID).Methods(methodID).DetailedDescription

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.

Initialization <b>must</b> be called first in any client code."

• 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:

C++ Signature: static void xercesc_3_1::XMLPlatformUtils::Initialize


• In the DetailedDescription argument, replace This content is from the external
library documentation with the new content. The line now reads:
"DetailedDescription", "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." + newline + ...

• Save the file.


• Review the updated help text.

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.

Initialization <b>must</b> be called first in any client code."

Build Library and Display Help


• build(defineMyXercesLibrary)
• Add the library to your path. Either click the link in the message or type:

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.

Initialization <b>must</b> be called first in any client code.

Inputs
locale read-only string
locale The locale to use for messages.

nlsHome read-only string


nlsHome User specified location where MsgLoader retrieves error message files.
the discussion above with regard to locale, applies to nlsHome as well.

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

C++ Limitation Workaround Examples


If your shared library contains data types or language features not supported by the MATLAB
interface to C++ libraries, you might be able to include this functionality by creating a wrapper
header file. This topic provides examples for some limitations. For more information, see “Limitations
to C/C++ Support” on page 5-40.

To run the workaround examples on Windows:

• Copy the C++ header file statements into .hpp files.


• Copy the source code into .cpp files and build, using instructions in “Build Example Shared
Library Files on Windows” on page 5-79.
• Execute the MATLAB code to build the interface.
• If required, edit the library definition file.
• Execute the MATLAB code to test the functionality.

Class Objects in std Namespace


A MATLAB interface to a C++ library does not include functions that use objects defined in the std
namespace. For example, the functions in this Student.hpp header file pass std::stack objects. If
you build the MATLAB interface, functions readStudents and getStudents are not included.
#ifndef STUDENT_HEADER
#define STUDENT_HEADER

#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

class DLL_EXPORT Student {


int rollNumber;
public:
Student();
Student(int rollNo);
int getRollNumber();
};

DLL_EXPORT void readStudents(const std::stack<Student>& students);

DLL_EXPORT std::stack<Student> getStudents(int size);

#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) {}

Student::Student(int rollNo) : rollNumber(rollNo) {}

int Student::getRollNumber() {
return rollNumber;
}

DLL_EXPORT void readStudents(const std::stack<Student>& students) {


}

DLL_EXPORT std::stack<Student> getStudents(int size) {


std::stack<Student> students;
for (int i = 0; i < size; i++) {
students.push(Student(i+1));
}
return students;
}
2 Create the Student.hpp header file and put it with the Student.dll shared library file in a
folder identified as rtpath.
3 Create a class CStack to represent an std::stack object. Put this definition in a header file
CStack.hpp.
//Wrapper header to access/pass std::stack objects from MATLAB
#ifndef stack_header
#define stack_header

#include <stack>
#include <stdexcept>

template<typename T>
class CStack {
std::stack<T> data;
public:
CStack() {}

// This parameterized constructor is required for the wrapper functions


// and is not included in the MATLAB interface
CStack(const std::stack<T>& d):data(d) {}

// Function to access the topmost element in stack


T* get() {
if (data.empty())
throw std::runtime_error("Retrieving element from Empty Stack");
return &data.top();
}

// Function to remove elements from stack


void remove() {
if (data.empty())
throw std::runtime_error("Stack is empty");
data.pop();
}

// Function to add elements to stack


void add(const T* element) {
data.push(*element);
}

// This method is required for the wrapper functions, and


// is not included in the MATLAB interface
const std::stack<T>& getData() const{
return data;
}

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"

//wrapper function to access the function that accepts std::stack input


void readStudentsWrapper(const CStack<Student>& students) {
readStudents(students.getData());
}

//wrapper function to access the function that returns the std::stack


CStack<Student> getStudentsWrapper(int size) {
auto students = getStudents(size);
CStack<Student> cstackStudents(students);
return cstackStudents;
}
5 Generate a library definition in a package named stack.
clibgen.generateLibraryDefinition(["Student.hpp","StudentWrapper.hpp"],"PackageName","stack",...
"Libraries","Student.lib","TreatObjectPointerAsScalar",true,"Verbose",true);

Warning: File 'manifest.json' not found.


Warning: Some C++ language constructs in the header file are not supported and not imported.

Did not add 'readStudents' at Student.hpp:24.


Type 'stack' is from std namespace or system header and is not supported.

Did not add 'getStudents' at Student.hpp:26.


Type 'stack' is from std namespace or system header and is not supported.

Did not add constructor to class 'CStack<Student>' at CStack.hpp:16.


Type 'stack' is from std namespace or system header and is not supported.

Did not add member 'getData' to class 'CStack<Student>' at CStack.hpp:39.


Type 'stack' is from std namespace or system header and is not supported.

Using MinGW64 Compiler (C++) compiler.


Generated definition file definestack.mlx and data file 'stackData.xml'
contain definitions for 13 constructs supported by MATLAB.
Build using build(definestack).

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

student = studentsStack.get; % returns topmost element from studentStack


studentsStack.remove % removes topmost element of stack

Class Templates With Incomplete or Missing Instantiations


A MATLAB interface to a C++ library does not support uninstantiated template classes. For example,
the class Pairs in this Templates.hpp header file is not instantiated.

// Header for Template class


#ifndef templates_Header
#define templates_Header

template <class T>


class Pairs {
public:
T val1;
T val2;
Pairs() : val1(0), val2(0) {}
Pairs(T first, T second) : val1(first), val2(second) {}
T getVal1() {
return val1;
}
T getVal2() {
return val2;
}
};
#endif

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"

/* Data types that will be used for Pairs class. */


template class Pairs<int>;
template class Pairs<double>;
2 Generate the library definition.
clibgen.generateLibraryDefinition(["TemplatesWrapper.hpp","Templates.hpp"],"PackageName","Templates","Verbose",true)

Generated definition file defineTemplates.mlx and data file 'TemplatesData.xml'


contain definitions for 16 constructs supported by MATLAB.
Build using build(defineTemplates).
3 Build the interface.

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

DLL_EXPORT double getArea(int radius, double piVal);

#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"

DLL_EXPORT double getArea(int radius, double piVal) {


return piVal*radius*radius;
}
2 Create the Area.hpp header file and put it with the Area.dll shared library file in a folder
identified as rtpath.
3 To include PI, create this wrapper header file WrapperPI.hpp which defines function getPI to
get the value of the preprocessor directive.
//Wrapper to access the preprocessor directive value
#include "Area.hpp"

double getPI(){ //Wrapper function retrieves the value of PI


return PI;
}
4 Generate the library definition.
clibgen.generateLibraryDefinition(["Area.hpp","WrapperPI.hpp"],"PackageName","Area",...
"Libraries","Area.lib","TreatObjectPointerAsScalar",true,"Verbose",true)
5 Build the interface.
build(defineArea)
addpath('Area')
6 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]);

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.

//Header file which accepts and return the vector of std::string


#ifndef stringVec_header
#define stringVec_header
#include <vector>
#include <string>

#ifdef _WIN32
#ifdef EXPORT
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#else
#define DLL_EXPORT __attribute__((visibility ("default")))
#endif

DLL_EXPORT void readStringVector(const std::vector<std::string>& stringVector); //readStringVecto

DLL_EXPORT std::vector<std::string> getStringVector(int size); //getStringVector function gets dr

#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"

DLL_EXPORT void readStringVector(const std::vector<std::string>& stringVector) {


}

DLL_EXPORT std::vector<std::string> getStringVector(int size) {


std::vector<std::string> stringVector;
for (int i = 0; i < size; i++) {
stringVector.push_back(("string"+ std::to_string(i+1)));
}
return stringVector;
}
2 Create the StringVector.hpp header file and put it with the StringVector.dll shared
library file in a folder identified as rtpath.

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(const std::vector<T>& d): data(d)


• Move 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:

void add(const T& element)


• Method to get data from vectors:

const std::vector<T>& getData() const

CVector.hpp defines this class.


//Wrapper header to access/pass std::vector from MATLAB
#ifndef cvector_header
#define cvector_header

#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>

void wrapperReadStringVector(const CVector<std::string>& stringVec) {


readStringVector(stringVec.getData());
}

CVector<std::string> wrapperGetStringVector(int size) {


auto strVec = getStringVector(size);
CVector<std::string> cvecString(strVec);
return cvecString;
}
5 Generate the library definition.
clibgen.generateLibraryDefinition(["StringVector.hpp","WrapperStringVector.hpp"],"PackageName","StringVector",...
"Libraries","StringVector.lib","TreatObjectPointerAsScalar",true,"Verbose",true)
6 Build the interface.

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;

% Add elements to vector


stringVectorObj.add("Jack");
stringVectorObj.add("John");
stringVectorObj.add("Joe");

% Call function with std::string vector input with CVector


clib.StringVector.wrapperReadStringVector(stringVectorObj);
clear stringVectorObj;

Build Example Shared Library Files on Windows


At the Windows command prompt, add the path to the MinGW-w64 compiler to the system path. For
example, if the compiler is at mingwpath, then type:

mingwpath = 'mingwpathname';
set PATH=mingwpath;%PATH%

Navigate to the location of C++ source files.

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

Use C++ Objects and Functions in parfor Loops


You can use the MATLAB parfor function with a MATLAB interface to a C++ shared library.

• 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.

The following use cases are not supported.

• 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

Initialize Pointer Members of C++ Structures for MATLAB


Interface to Library
Although your code might first allocate a struct and subsequently assign values to its members, the
MATLAB interface does not support assigning a new object to a pointer member. For example, this
header defines a struct variable S2 with a member pointer to struct S1.

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

C++ Language Opaque Objects


An opaque object has no properties and methods visible to MATLAB. You can pass these objects to
related functions that know how to work with them. Consult the documentation for the function that
returned the opaque object to learn more about how to use it.

For example, this C++ code defines SessionHandle as typedef void*.

typedef void* SessionHandle;


SessionHandle getHandle(){
// implement code here
};
void closeHandle(void * SessionHandle){};

After generating the MATLAB interface lib, call getHandle:

sessionHandle = clib.lib.getHandle

sessionHandle =
SessionHandle is an opaque object.

The help for SessionHandle is:

clib.lib.SessionHandle C++ opaque type.

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

Define void* and void** Arguments


MATLAB supports C++ signatures that have void* inputs or that return void* outputs. A void*
return type and a void** parameter type are opaque objects on page 5-82.

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.

MATLAB does not support type-casting void* to MATLAB data types.

void* Return Types


MATLAB defines void* output in the library definition file by specifying the argument MLTYPE as one
of these:

• A typedef from the library. Use for scalar output only.

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.

typedef void* handle;


handle getHandle();

using ghandle = void*;


ghandle getGHandle();

void* getImagData(const int* pa);

typedef void* data;


void* getData();

Define Output Argument by Using typedef from Library

handle is defined by typedef. MATLAB creates the opaque type typedef void* handle.

5-83
5 Calling Functions in C++ Shared Libraries from MATLAB

handleDefinition = addOpaqueType(libnameDef, ...


"typedef void* handle", "MATLABName", ...
"clib.libname.handle", ...
"Description", "clib.libname.handle Representation of C++ type void*.")

MATLAB automatically uses this type to define MLTYPE as clib.libname.handle in the return
argument.
defineOutput(getHandleDefinition, "RetVal", "clib.lib.handle");

Define Output Argument from using Statement

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");

Define Output Argument from New Type Name

The output of getImagData needs definition.


%defineOutput(getImagDataDefinition, "RetVal", <MLTYPE>, <SHAPE>); ...
%'<MLTYPE>' can be an existing typedef name for void* or a new typedef name to void*.

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);

Define Output Argument from Existing typedef

The output of getData needs definition.


%defineOutput(getDataDefinition, "RetVal", <MLTYPE>, <SHAPE>);
%'<MLTYPE>' can be an existing typedef name for void* or a new typedef name to void*.

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);

void* Input Argument Types


MATLAB attempts to convert the underlying C++ data of a void* argument to the corresponding C+
+ type. For information about the C++ to MATLAB data type mapping, see “void* Argument Types”
on page 5-57. The data mapping is.

• 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

Define Input Argument as Fundamental Type

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);

MATLAB generates this statement for defining input argument value.


%defineArgument(getAttributeDefinition, "value", <MLTYPE>, <DIRECTION>, <SHAPE>);
%'<MLTYPE>' can be primitive type, user-defined type, clib.array type, or
%a list of existing typedef names for void*.

Define value as a scalar return value of type uint64.


defineArgument(getAttributeDefinition, "value", "uint64", "output", 1);

Define Input Argument as clib.array Type

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);

Define argument void *readArray as an input of type clib.array.libname.Int with a size of


arraySizeInBytes.
defineArgument(readRawDefinition, "readArray", "clib.array.libname.Int", ...
"input", "arraySizeInBytes");

Define Input Argument as C++ Class in Library

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;
....
}

Define argument void *userdata as an input scalar of class clib.lib.cv.ogl.Texture2D.


defineArgument(setDrawCallbackDefinition, "userdata", "clib.lib.cv.ogl.Texture2D", ...
"input", 1);

Define Input Argument as Existing void* typedef

You can define the in argument in this setRemoteTimeout function by using an existing typedef
for void*.
typedef void* sessionHandle;
void setRemoteTimeout(sessionHandle in);

Define argument in as an input scalar of typedef sessionHandle.


defineArgument(setRemoteTimeoutDefinition, "in", "clib.libname.sessionHandle", "input", 1);

void** Input Argument Types


MATLAB returns a void* argument for void** parameters. If void * is defined by using a
typedef or a using statement, then MATLAB automatically assigns the typedef or using name as
the MLTYPE. Otherwise, you can assign a MATLAB type to an existing void* type in the library by
specifying MLTYPE in the library definition file.

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();
}

void getNewHandle(void** out){


*out = new int(1);
}
typedef void* ptr;
void getPointer(void** out){
*out = new int(2);
}

Define Argument With void* typedef or using Statement From Library

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);

Define Argument From New Type Name for void*

The void** parameter of getNewHandle needs definition.

%defineArgument(getNewHandleDefinition, "out", <MLTYPE>, "output", 1);

You can specify a new type, for example clib.lib.NewHandle.

defineArgument(getNewHandleDefinition, "out", "clib.lib.NewHandle", "output", 1);

Define Argument From Existing void* typedef

The void** parameter of getNewHandle needs definition.

%defineArgument(getPointerDefinition, "out", <MLTYPE>, "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.

defineArgument(getPointerDefinition, "out", "clib.lib.ptr", "output", 1);

5-86
Define void* and void** Arguments

MATLABType as Object of Class


MATLAB displays a message about an object not available without constructing an object of the class
and suggests other values for MATLABType. Alternatively, consider using a MATLABType that is
outside the scope of the class.

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.");

AConstructor1Definition = addConstructor(ADefinition, ...


"A::A(void * in)", ...
"Description", "clib.lib.A.A Constructor of C++ class A.");
defineArgument(AConstructor1Definition, "arg1", "clib.lib.A.NewHandle", "input", 1);
% '<MLTYPE>' can be primitive type, user-defined type, clib.array type, or a list of existing typedef names for void*.
defineArgument(AConstructor1Definition, "arg2", "clib.lib.A.handle", "input", 1);
% '<MLTYPE>' can be clib.lib.A.handle, primitive type, user-defined type, or a clib.array type.
validate(AConstructor1Definition);

task1Definition = addMethod(ADefinition, ...


"A::handle A::task1()", ...
"Description", "clib.lib.A.task1 Method of C++ class A.");
defineOutput(task1Definition, "RetVal", "clib.lib.A.NewHandle", 1);
% '<MLTYPE>' can be an existing typedef name for void* or a new typedef name to void*.
validate(task1Definition);

task2Definition = addMethod(ADefinition, ...


"A::handle A::task2()", ...
"Description", "clib.lib.A.task2 Method of C++ class A.");
defineOutput(task2Definition, "RetVal", "clib.lib.A.handle", 1);
validate(task2Definition);

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:

• Primitive type, user-defined type, or clib.array type for arg1.


• Primitive type, user-defined type, clib.array type for arg2.

5-87
5 Calling Functions in C++ Shared Libraries from MATLAB

• MATLABType, which is outside the scope of clib.lib.A.

Memory Management for void* and void** Arguments


You can pass the ownership of the memory of a void* argument to the library by using the
'ReleaseOnCall' name-value argument in defineArgument (FunctionDefinition) or
defineArgument (MethodDefinition).

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

Use Function Type Arguments


MATLAB supports C++ signatures with std::function and C function pointer arguments. Both
std::function and C function pointer are function types in MATLAB. C function pointers and
std::function are not supported as function return types or data members.

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.

using funcPtrType = std::function<void(int*,int)>;


void task(int *arr, int len , funcPtrType fp){
fp(arr, len);
}

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.type.libname.FunctionN, where N is 1 for the first function type without a typedef


and incremented for additional function types in libname. For example, libname contains these
functions:

void task1((void (*param)(int));


void task2((void (*param)(long));

The MATLAB signatures for the functions are:

clib.libname.task1(clib.type.libname.Function1)
clib.libname.task2(clib.type.libname.Function2)

Call C++ Functions With Function Type Input


Pass C++ Library Function

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

using funcPtrType = std::function<void(int*,int)>;


void callFunc_inputoutput(int *arr, int len , funcPtrType fp){
fp(arr, len);
}

Call callFunc_inputoutput with the double_inputoutput function.


fp = @clib.test2.double_inputoutput;
arr = [1,2,3,4,5,6];
clib.test2.callFunc_inputoutput(arr,fp)

Help for Function

help clib.test2.double_inputoutput
clib.test2.double_inputoutput Representation of C++ function double_inputoutput.

Inputs
arr int32

Outputs
arr int32

Choose Input Function to Function Type

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

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.

class A{}; // User type


template<typename T> void show(T a) {}
template void show<int>(int);
template void show<double>(double);
template<> void show<const A &>(const A& a){}

Build interface libname, then display help for the show function. MATLAB displays the calling syntax
for three functions.

help clib.libname.show

clib.libname.show Representation of C++ function show.

Inputs
a int32

No outputs

Other clib.libname.show functions:

clib.libname.show Representation of C++ function show.

Inputs
a double

No outputs

clib.libname.show Representation of C++ function show.

Inputs
a read-only clib.libname.A

No outputs

If you type:

var = pi;
clib.libname.show(var)

then MATLAB chooses the signature with input type double.

Unique Function Names


The C++ interface also generates unique function names based on the signature types. To view the
unique names for the show function, type:

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.

Functions contained in clib.libname:


show - clib.libname.show Representation of C++ function show.

show_AConst__ - clib.libname.show Representation of C++ function show.

show - clib.libname.show Representation of C++ function show.

show_double_ - clib.libname.show Representation of C++ function show.

show - clib.libname.show Representation of C++ function show.

show_int_ - clib.libname.show Representation of C++ function show.

To call the type-specific function for input of type double, type:

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.

Verify Selected C++ Compiler


You can use any C++ compiler supported by MathWorks. To verify that you have a C++ compiler,
type:

mex -setup cpp

This example uses the MinGW64 Compiler (C++) for C++ language compilation.

Generate Definition File


Identify the names and paths to the C++ library artifacts. By default, the function uses the name of
the header file (matrixOperations) as the name of the library (libname).
productPath = fullfile(matlabroot,'extern','examples','cpp_interface');
hppFile = 'matrixOperations.hpp';
cppFile = 'matrixOperations.cpp';

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

C++ compiler set to 'MinGW64 Compiler (C++)'.


Definition file definematrixOperations.mlx contains definitions for 10 constructs supported by MATLAB.
- 5 construct(s) are fully defined.
- 5 construct(s) partially defined and commented out.

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.

Open Definition File


Open the generated definition file in Live Editor by clicking the link in the output message. Then
continue with the next step.

See Also
clibgen.generateLibraryDefinition

5-93
5 Calling Functions in C++ Shared Libraries from MATLAB

Generate Interface on Windows


This example creates a library definition file for a library with an import library file on Windows.

Verify Selected C++ Compiler


You can use any C++ compiler supported by MathWorks. This example uses the MinGW64 Compiler
(C++) for C++ language compilation. To verify that you have a C++ compiler, type:

mex -setup cpp

Generate Definition File


Identify the names and paths to the C++ library artifacts.
productPath = fullfile(matlabroot,"extern","examples","cpp_interface");
hppFile = "matrixOperations.hpp";
hppPath = productPath;
libFile = "matrixOperations.lib";
libname = "matrixlib";

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.

C++ compiler set to 'MinGW64 Compiler (C++)'.


Definition file definematrixlib.mlx contains definitions for 10 constructs supported by MATLAB.
- 5 construct(s) are fully defined.
- 5 construct(s) partially defined and commented out.

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).

Open Definition File


Open the generated definition file in Live Editor by clicking the link in the output message. Then
continue with the next step.

See Also
clibgen.generateLibraryDefinition

5-94
Header File and Shared Object File on Linux

Header File and Shared Object File on Linux


This example creates a MATLAB interface to a C++ library matrixOperations for Linux. The
library is defined by header file matrixOperations.hpp and shared object file
libmwmatrixOperations.so.

MATLAB provides these files in this folder:

fullfile(matlabroot,"extern","examples","cpp_interface");

Use these steps to create a matrixOperations interface for Linux.

1 “Generate Interface on Linux” on page 5-96


2 “Define Missing Constructs” on page 5-100
3 “Build Interface” on page 5-110
4 “Call Library Functions on Linux” on page 5-116

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 Interface on Linux


This example creates a library definition file definematrixlib.mlx for a library with a shared
object file on Linux.

Verify Selected C++ Compiler


You can use any C++ compiler supported by MathWorks. This example uses the g++ compiler for C+
+ language compilation. To verify that you have a C++ compiler, type:

mex -setup cpp

Generate Definition File


Identify the names and paths to C++ library artifacts.
productPath = fullfile(matlabroot,"extern","examples","cpp_interface");
libPath = fullfile(productPath,"glnxa64");
hppFile = "matrixOperations.hpp";
hppPath = productPath;
libFile = "libmwmatrixOperations.so";

% Name the interface


libname = "matrixlib";

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.

Using g++ compiler.


Definition file definematrixlib.mlx contains definitions for 10 constructs supported by MATLAB.
- 5 construct(s) are fully defined.
- 5 construct(s) partially defined and commented out.

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).

Open Definition File


Open the generated definition file in Live Editor by clicking the link in the output message. Then
continue with the next step.

See Also
clibgen.generateLibraryDefinition

5-96
Generate Interface on macOS

Generate Interface on macOS


This example creates a library definition file definematrixlib.mlx for a library with a dynamic
shared library file on macOS.

Verify Selected C++ Compiler


You can use any C++ compiler supported by MathWorks. To verify that you have a C++ compiler,
type:

mex -setup cpp

This example uses the g++ compiler.

Generate Definition File


Identify the names and paths to C++ library artifacts.
productPath = fullfile(matlabroot,"extern","examples","cpp_interface");
libPath = fullfile(productPath,"maci64");
hppFile = "matrixOperations.hpp";
hppPath = productPath;
libFile = "libmwmatrixOperations.dylib";

% Name the interface


libname = "matrixlib";

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.

Using g++ compiler.


Definition file definematrixlib.mlx contains definitions for 10 constructs supported by MATLAB.
- 5 construct(s) are fully defined.
- 5 construct(s) partially defined and commented out.

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).

Open Definition File


Open the generated definition file in Live Editor by clicking the link in the output message. Then
continue with the next step.

See Also
clibgen.generateLibraryDefinition

5-97
5 Calling Functions in C++ Shared Libraries from MATLAB

Define Missing Constructs


When you created the library definition file to the matrixOperations library in the previous step,
MATLAB reported that five constructs are partially defined. To completely define the functionality,
edit the definematrixlib.mlx file. If you have not yet opened the file, you can click the link in the
output message to open it in Live Editor.
Warning: Some C++ language constructs in the files for generating interface file are not supported and not imported.

C++ compiler set to 'MinGW64 Compiler (C++)'.


Definition file definematrixlib.mlx contains definitions for 10 constructs supported by MATLAB.
- 5 construct(s) are fully defined.
- 5 construct(s) partially defined and commented out.

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.

• setMat - C++ method for class Mat


• getMat - C++ method for class Mat
• copyMat - C++ method for class Mat
• addMat - C++ package function
• updateMatBySize - C++ package function

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.

1 For each construct, uncomment the statements defining it.


2 Replace <SHAPE> arguments with these values.

Construct Argumen Argument C++ Description Replac


t Name Definition e
<SHAPE
> with
Value
setMat src int [] src The length of the matrix is "len"
defined by the input argument
len.
getMat RetVal int const * The length of the output "len"
argument is defined by the
input argument len.
copyMat dest int * dest The length dest is defined by "len"
the input argument len.
addMat mat Mat const * mat The function takes a single 1
mat argument.
updateMatByS arr int * arr The length arr is defined by "len"
ize the input argument len.

5-98
Define Missing Constructs

3 Save and close the definition file.


4 Continue with the next step.

See Also

5-99
5 Calling Functions in C++ Shared Libraries from MATLAB

Define Missing Constructs


When you created the library definition file to the matrixOperations library in the previous step,
MATLAB reported that five constructs are partially defined. To completely define the functionality,
edit the definematrixlib.mlx file. If you have not yet opened the file, you can click the link in the
output message to open it in Live Editor.
Definition file definematrixlib.mlx contains definitions for 10 constructs supported by MATLAB.
- 5 construct(s) are fully defined.
- 5 construct(s) partially defined and commented out.

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.

• setMat - C++ method for class Mat


• getMat - C++ method for class Mat
• copyMat - C++ method for class Mat
• addMat - C++ package function
• updateMatBySize - C++ package function

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.

1 For each construct, uncomment the statements defining it.


2 Replace <SHAPE> arguments with these values.

Construct Argumen Argument C++ Description Replac


t Name Definition e
<SHAPE
> with
Value
setMat src int [] src The length of the matrix is "len"
defined by the input argument
len.
getMat RetVal int const * The length of the output "len"
argument is defined by the
input argument len.
copyMat dest int * dest The length dest is defined by "len"
the input argument len.
addMat mat Mat const * mat The function takes a single 1
mat argument.
updateMatByS arr int * arr The length arr is defined by "len"
ize the input argument len.
3 Save and close the definition file.
4 Continue with the next step.

5-100
Define Missing Constructs

See Also

5-101
5 Calling Functions in C++ Shared Libraries from MATLAB

Define Missing Constructs


When you created the library definition file to the matrixOperations library in the previous step,
MATLAB reported that five constructs are partially defined. To completely define the functionality,
edit the definematrixlib.mlx file. If you have not yet opened the file, you can click the link in the
output message to open it in Live Editor.

Definition file definematrixlib.mlx contains definitions for 10 constructs supported by MATLAB.


- 5 construct(s) are fully defined.
- 5 construct(s) partially defined and commented out.

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.

• setMat - C++ method for class Mat


• getMat - C++ method for class Mat
• copyMat - C++ method for class Mat
• addMat - C++ package function
• updateMatBySize - C++ package function

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.

1 For each construct, uncomment the statements defining it.


2 Replace <SHAPE> arguments with these values.

Construct Argumen Argument C++ Description Replac


t Name Definition e
<SHAPE
> with
Value
setMat src int [] src The length of the matrix is "len"
defined by the input argument
len.
getMat RetVal int const * The length of the output "len"
argument is defined by the
input argument len.
copyMat dest int * dest The length dest is defined by "len"
the input argument len.
addMat mat Mat const * mat The function takes a single 1
mat argument.
updateMatByS arr int * arr The length arr is defined by "len"
ize the input argument len.

5-102
Define Missing Constructs

3 Save and close the definition file.


4 Continue with the next step.

See Also

5-103
5 Calling Functions in C++ Shared Libraries from MATLAB

Define Missing Constructs


When you created the library definition file to the matrixOperations library in the previous step,
MATLAB reported that five constructs are partially defined. To completely define the functionality,
edit the definematrixlib.mlx file. If you have not yet opened the file, you can click the link in the
output message to open it in Live Editor.
Warning: Some C++ language constructs in the files for generating interface file are not supported and not imported.

C++ compiler set to 'MinGW64 Compiler (C++)'.


Definition file definematrixlib.mlx contains definitions for 10 constructs supported by MATLAB.
- 5 construct(s) are fully defined.
- 5 construct(s) partially defined and commented out.

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.

• setMat - C++ method for class Mat


• getMat - C++ method for class Mat
• copyMat - C++ method for class Mat
• addMat - C++ package function
• updateMatBySize - C++ package function

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.

1 For each construct, uncomment the statements defining it.


2 Replace <SHAPE> arguments with these values.

Construct Argumen Argument C++ Description Replac


t Name Definition e
<SHAPE
> with
Value
setMat src int [] src The length of the matrix is "len"
defined by the input argument
len.
getMat RetVal int const * The length of the output "len"
argument is defined by the
input argument len.
copyMat dest int * dest The length dest is defined by "len"
the input argument len.
addMat mat Mat const * mat The function takes a single 1
mat argument.
updateMatByS arr int * arr The length arr is defined by "len"
ize the input argument len.

5-104
Define Missing Constructs

3 Save and close the definition file.


4 Continue with the next step.

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

Validate Edits to Library Definition File


In the previous step, you modified the library definition file definematrixlib.mlx. To verify the
MATLAB statements, validate the file and fix any reported errors in the file.

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 Interface and Add to MATLAB Path


Build the matrixlib interface to the library.

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')

Either click the addpath link in the message or type:

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.

To call functions in the library, continue with the next step.

5-106
Build Interface

See Also

5-107
5 Calling Functions in C++ Shared Libraries from MATLAB

Build Interface

Validate Edits to Library Definition File


In the previous step, you modified the library definition file definematrixlib.mlx. To verify the
MATLAB statements, validate the file and fix any reported errors in the file.

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 Interface and Add to MATLAB Path


Build the matrixlib interface to the library.

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')

Either click the addpath link in the message or type:

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.

To call functions in the library, continue with the next step.

5-108
Build Interface

See Also

5-109
5 Calling Functions in C++ Shared Libraries from MATLAB

Build Interface

Validate Edits to Library Definition File


In the previous step, you modified the library definition file definematrixlib.mlx. To verify the
MATLAB statements, validate the file and fix any reported errors in the file.

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 Interface and Add to MATLAB Path


Build the matrixlib interface to the library.

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')

Either click the addpath link in the message or type:

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.

To call functions in the library, continue with the next step.

5-110
Build Interface

See Also

5-111
5 Calling Functions in C++ Shared Libraries from MATLAB

Build Interface to matrixoperations Library

Validate Edits to Library Definition File


In the previous step, you modified the library definition file definematrixlib.mlx. To verify the
MATLAB statements, validate the file and fix any reported errors in the file.

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)

MATLAB Interface to matrixOperations Library

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 Interface and Add to MATLAB Path


Build the matrixOperations interface to the library.

build(definematrixOperations)

Building interface file 'matrixOperationsInterface.dll' for clib package 'matrixOperations'.


Interface file 'matrixOperationsInterface.dll' built in folder 'C:\Users\Documents\MATLAB\matrixOperations'.

To use the library, add the interface file folder to the MATLAB path.
addpath('C:\Users\Documents\MATLAB\matrixOperations')

Either click the addpath link in the message or type:

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

To call functions in the library, continue with the next step.

See Also
build | summary

5-113
5 Calling Functions in C++ Shared Libraries from MATLAB

Call Library Functions on Windows


In the previous step, you built a MATLAB interface to the C++ matrixOperations library.
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')

Set System Path to Library File


Add the path to the C++ shared library file to the beginning of your system path. For more
information, see “Set Run-Time Library Path for C++ Interface” on page 5-6.
dllPath = fullfile(matlabroot,'extern','examples','cpp_interface','win64','mingw64');
syspath = getenv('PATH');
setenv('PATH',[dllPath ';' syspath]);

To verify the updated system path, type:

syspath = split(getenv('PATH'),';')

Set MATLAB Path to Interface Folder


Add the MATLAB interface file to the MATLAB path.

addpath('matrixlib')

View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.

doc clib.matrixlib.Mat %load the package


doc clib.matrixlib %display package members

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.

Call Library Functions


To create a Mat object and call functions in the library, type:

matObj = clib.matrixlib.Mat; % Create a Mat object


intArr = [1,2,3,4,5];
matObj.setMat(intArr); % Set the values to intArr
retMat = matObj.getMat(5) % Display the values

retMat = 1×5 int32 row vector


1 2 3 4 5

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

Call Library Functions on Linux


In the previous step, you built a MATLAB interface to the C++ matrixOperations library.

Set System Path to Library File


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.

setenv LD_LIBRARY_PATH rtPath

where rtPath is the output of:


rtPath = fullfile(matlabroot,'extern','examples','cpp_interface','glnxa64')

Start MATLAB in the same system prompt where you set the LD_LIBRARY_PATH variable.

To verify the updated system path, in MATLAB type:

syspath = split(getenv('LD_LIBRARY_PATH'),';')

Set MATLAB Path


To add the MATLAB interface file to the MATLAB path, navigate to the folder you used in the
“Generate Interface on Linux” on page 5-96 step.

addpath('matrixlib')

View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.

doc clib.matrixlib.Mat %load the package


doc clib.matrixlib %display package members

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.

Call Library Functions


To create a Mat object and call functions in the library, type:

matObj = clib.matrixlib.Mat; % Create a Mat object


intArr = [1,2,3,4,5];
matObj.setMat(intArr); % Set the values to intArr
retMat = matObj.getMat(5) % Display the values

retMat = 1×5 int32 row vector


1 2 3 4 5

5-116
Call Library Functions on Linux

See Also

5-117
5 Calling Functions in C++ Shared Libraries from MATLAB

Call Library Functions on macOS


In the previous step, you built a MATLAB interface to the C++ matrixOperations library.

Set System Path to Library File


At the Terminal 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.

setenv DYLD_LIBRARY_PATH rtPath

where rtPath is the output of:


rtPath = fullfile(matlabroot,'extern','examples','cpp_interface','maci64')

Start MATLAB in the same system prompt where you set the DYLD_LIBRARY_PATH variable.

To verify the updated system path, in MATLAB type:

syspath = split(getenv('DYLD_LIBRARY_PATH'),';')

Set MATLAB Path


To add the MATLAB interface file to the MATLAB path, navigate to the folder you used in the
“Generate Interface on macOS” on page 5-97 step.

addpath('matrixlib')

View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.

doc clib.matrixlib.Mat %load the package


doc clib.matrixlib %display package members

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.

Call Library Functions


To create a Mat object and call functions in the library, type:

matObj = clib.matrixlib.Mat; % Create a Mat object


intArr = [1,2,3,4,5];
matObj.setMat(intArr); % Set the values to intArr
retMat = matObj.getMat(5) % Display the values

retMat = 1×5 int32 row vector


1 2 3 4 5

5-118
Call Library Functions on macOS

See Also

5-119
5 Calling Functions in C++ Shared Libraries from MATLAB

Call matrixoperations Library Functions


In the previous step, you built a MATLAB interface to the C++ matrixOperations library.
Building interface file 'matrixOperationsInterface.dll' for clib package 'matrixOperations'.
Interface file 'matrixOperationsInterface.dll' built in folder 'C:\Users\Documents\MATLAB\matrixOperations'.

To use the library, add the interface file folder to the MATLAB path.
addpath('C:\Users\Documents\MATLAB\matrixOperations')

Set MATLAB Path


addpath('matrixOperations')

View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.

doc clib.matrixOperations.Mat %load the package


doc clib.matrixOperations %display package members

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.

Call Library Functions


To create a Mat object and call functions in the library, type:

matObj = clib.matrixOperations.Mat; % Create a Mat object


intArr = [1,2,3,4,5];
matObj.setMat(intArr); % Set the values to intArr
retMat = matObj.getMat(5) % Display the values

retMat = 1×5 int32 row vector


1 2 3 4 5

See Also

5-120
Generate Interface to school Library

Generate Interface to school Library

Verify Selected C++ Compiler


You can use any C++ compiler supported by MathWorks. To verify that you have a C++ compiler,
type:

mex -setup cpp

This example uses the MinGW64 compiler.

Generate Definition File


Identify the name and path to the C++ library artifacts. By default, the function uses the name of the
header file (school) as the name of the library (libname).
productPath = fullfile(matlabroot,'extern','examples','cpp_interface');
hppFile = 'school.hpp';

Generate the library definition file. MATLAB creates the definition file defineschool.mlx.
clibgen.generateLibraryDefinition(fullfile(productPath,hppFile),...
"OverwriteExistingDefinitionFiles",true)

Open Definition File


Open the generated definition file in Live Editor by clicking the link in the output message. Then
continue with the next step.

See Also
clibgen.generateLibraryDefinition

5-121
5 Calling Functions in C++ Shared Libraries from MATLAB

Define Missing Constructs in Interface to school Library


When you created the library definition file in the previous step, MATLAB reports that one construct
requires additional information (definition). This means that MATLAB cannot automatically define the
signature for one of the functions. To provide the missing information, click the link to open
defineschool.mlx in MATLAB Live Editor.

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>);

defineArgument(getNameDefinition, "p", "clib.school.Person", "input", 1);

Save and close the definition file.

Continue with the next step.

See Also

Related Examples
• “Define Missing SHAPE Parameter” on page 5-28

5-122
Build Interface to school Library

Build Interface to school Library


Validate Edits to Library Definition File
In the previous step, you modified the library definition file. To verify the MATLAB statements,
validate the file and fix any reported errors in the file.
defineschool;

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)

MATLAB Interface to school Library

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 Interface and Add to MATLAB Path


Build the school interface to the library.

build(defineschool)

Building interface file 'schoolInterface.dll' for clib package 'school'.


Interface file 'schoolInterface.dll' built in folder 'C:\Users\Documents\MATLAB\school'.

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.

To call functions in the library, continue with the next step.

See Also
build | summary

5-124
Call school Library Functions

Call school Library Functions

View Help
At the MATLAB command prompt, type these commands to open documentation for the library in
your help browser.

doc clib.school.Person %load the package


doc clib.school %display package members

Call Library Functions


To call functionality in the school library, use the MATLAB clib package.

Note Once you use a library class or function, you cannot modify the library definition unless you
restart MATLAB and rebuild the library.

Create a teacher and display the name

t1 = clib.school.Teacher('Ms. Jones',24);
getName(t1)

ans = "Ms. Jones"

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

Calling Functions in C Shared Libraries


from MATLAB

• “Call C Functions in Shared Libraries” on page 6-2


• “Invoke Library Functions” on page 6-3
• “View Library Functions” on page 6-4
• “Load and Unload Library” on page 6-5
• “Limitations to Shared Library Support” on page 6-6
• “Limitations Using Structures” on page 6-9
• “Loading Library Errors” on page 6-10
• “No Matching Signature Error” on page 6-11
• “MATLAB Terminates Unexpectedly When Calling Function in Shared Library” on page 6-12
• “Pass Arguments to Shared C Library Functions” on page 6-13
• “Shared Library shrlibsample” on page 6-17
• “Pass String Arguments Examples” on page 6-18
• “Pass Structures Examples” on page 6-20
• “Pass Enumerated Types Examples” on page 6-24
• “Pass Pointers Examples” on page 6-26
• “Pass Arrays Examples” on page 6-30
• “Iterate Through lib.pointer Object” on page 6-33
• “Represent Pointer Arguments in C Shared Library Functions” on page 6-35
• “Represent Structure Arguments in C Shared Library Functions” on page 6-37
• “Explore libstruct Objects” on page 6-38
• “MATLAB Prototype Files” on page 6-39
6 Calling Functions in C Shared Libraries from MATLAB

Call C Functions in Shared Libraries


A shared library is a collection of functions dynamically loaded by an application at run time. This
MATLAB interface supports libraries containing functions defined in C header files. To call functions
in C++ libraries, see the interface described in “C++ Libraries in MATLAB”.

MATLAB supports dynamic linking on all supported platforms.

Platform Shared Library File Extension


Microsoft Windows dynamic link library file .dll
Linux shared object file .so
Apple macOS dynamic shared library .dylib

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.

Details about using a shared library are in these topics.

• “Load and Unload Library” on page 6-5


• “View Library Functions” on page 6-4
• “Invoke Library Functions” on page 6-3

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.

• “Pass Arguments to Shared C Library Functions” on page 6-13


• “Manually Convert Data Passed to Functions” on page 6-15
• “Represent Pointer Arguments in C Shared Library Functions” on page 6-35
• “Represent Structure Arguments in C Shared Library Functions” on page 6-37

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

Invoke Library Functions


After loading a shared library into the MATLAB workspace, use the calllib function to call
functions in the library. The syntax for calllib is:

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

View Library Functions


To display information about library functions in the MATLAB Command Window, use the
libfunctions command.

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

Load and Unload Library


To give MATLAB access to functions in a shared library, first load the library into memory. After you
load the library, you can request information about library functions and call them directly from the
MATLAB command line.

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

Limitations to Shared Library Support


In this section...
“MATLAB Supports C Library Routines” on page 6-6
“Loading C++ Libraries” on page 6-6
“Limitations Using printf Function” on page 6-6
“Bit Fields” on page 6-6
“Enum Declarations” on page 6-7
“Unions Not Supported” on page 6-7
“Compiler Dependencies” on page 6-8
“Limitations Using Pointers” on page 6-8
“Functions with Variable Number of Input Arguments Not Supported” on page 6-8

MATLAB Supports C Library Routines


The MATLAB shared library interface supports C library routines only. Most professionally written
libraries designed to be used by multiple languages and platforms work fine. For more information,
see “Call C Functions in Shared Libraries” on page 6-2.

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.

Loading C++ Libraries


The shared library interface does not support C++ classes or overloaded functions elements. Use the
MATLAB C++ interface instead. For more information, see “C++ Libraries in MATLAB”.

Limitations Using printf Function


MATLAB does not display the output of the C printf function to the command window.

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;
};

edit the header file and replace it with:

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:

enum Enum1 {ValA='A',ValB='B'};

with:

enum Enum1 {ValA=65,ValB=66};

then rebuild the library.

Unions Not Supported


Unions are not supported. As a workaround, modify the source code taking out the union declaration
and replacing it with the largest alternative. Then, to interpret the results, write MATLAB code as
needed. For example, edit the source code and replace the following union:

struct mystruct
{
union
{
struct {char byte1,byte2;};
short word;
};
};

with:

struct mystruct
{
short word;
};

where on a little-endian based machine, byte1 is mod(f,256), byte2 is f/256, and


word=byte2*256+byte1. After editing the source code, rebuild the library.

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.

Limitations Using Pointers


Function Pointers

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.

Functions with Variable Number of Input Arguments Not Supported


The shared library interface does not support library functions with variable number of arguments,
represented by an ellipsis (...).

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

Limitations Using Structures

MATLAB Returns Pointers to Structures


MATLAB returns pointers to structures. Return by value is not supported.

Structure Cannot Contain Pointers to Other Structures


Nested structures or structures containing a pointer to a structure are not supported. However,
MATLAB can access an array of structures created in an external library.

Requirements for MATLAB Structure Arguments


When you pass a MATLAB structure to an external library function, the field names must meet the
following requirements.

• 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)

Requirements for C struct Field Names


When MATLAB loads a C struct definition, the field names in MATLAB are not case-sensitive. For
example, when you load a library containing the following definition, MATLAB does not create two
fields.

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

Loading Library Errors


Errors occur when the shared library is not a valid library. MATLAB displays messages similar to the
following:

There was an error loading the library "F:\mylibs\testlib.dll"


'F:\mylibs\testlib.dll' is not a valid shared library.

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

No Matching Signature Error


This error occurs when you call a function without the correct input or output arguments, or if there
is an error in the function signature in the header file.

For example, the function signature for the addStructByRef function in shrlibsample is:

[double, c_structPtr] addStructByRef(c_structPtr)

Load the library.

addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')

Create a structure, and call addStructByRef.

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')

Error using calllib


No method with matching signature.

The correct call is:

[res,st] = calllib('shrlibsample','addStructByRef',struct)

See Also
calllib | libfunctions

6-11
6 Calling Functions in C Shared Libraries from MATLAB

MATLAB Terminates Unexpectedly When Calling Function in


Shared Library
Some shared libraries, compiled as Microsoft Windows 32-bit libraries, use a calling convention that
is incompatible with the default MATLAB calling convention. The default calling convention for
MATLAB and for Microsoft C and C++ compilers is cdecl. For more information, see the MSDN®
Calling Conventions article.

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

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

C and MATLAB Equivalent Types


The shared library interface supports all standard scalar C types. The following table shows these C
types with their equivalent MATLAB types. MATLAB uses the type from the right column for
arguments having the C type shown in the left column.

Note All scalar values returned by MATLAB are of type double.

MATLAB Primitive Types

C Type Equivalent MATLAB Type


char, byte int8
unsigned char, byte uint8
short int16
unsigned short uint16
int int32
long (Windows) int32,
long
long (Linux) int64,
long
unsigned int uint32
unsigned long (Windows) uint32,
long
unsigned long (Linux) uint64,
long
float single
double double
char * char array (1xn)
*char[] cell array of character vectors

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

MATLAB Extended Types

C Pointer Type Argument Equivalent Example Function in


Data Type MATLAB Type “Shared Library
shrlibsample” on page
6-17
double * doublePtr double addDoubleRef
float * singlePtr single
intsize * (integer (u)int(size)Ptr (u)int(size) multiplyShort
pointer types) For example, int64 *
becomes int64Ptr.
byte[] int8Ptr int8
char[] (null-terminated cstring char array (1xn) stringToUpper
string passed by value)
char ** (array of stringPtrPtr cell array of character
pointers to strings) vectors
enum enumPtr
type ** typePtrPtr lib.pointer object allocateStruct
For example, double
**
becomes
doublePtrPtr.
void * voidPtr deallocateStruct
void ** voidPtrPtr lib.pointer object
struct (C-style structure MATLAB struct addStructFields
structure)
mxArray * MATLAB array MATLAB array
mxArray ** MATLAB arrayPtr lib.pointer object

How MATLAB Displays Function Signatures


Here are things to note about the input and output arguments shown in MATLAB function signatures.

• 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

Guidelines for Passing Arguments

• Nonscalar arguments must be declared as passed by reference in the library functions.


• If the library function uses single subscript indexing to reference a two-dimensional matrix, keep
in mind that C programs process matrices row by row. MATLAB processes matrices by column. To
get C behavior from the function, transpose the input matrix before calling the function, and then
transpose the function output.
• Use an empty array, [], to pass a NULL parameter to a library function that supports optional
input arguments. This notation is valid only when the argument is declared as a Ptr or PtrPtr as
shown by libfunctions or libfunctionsview.

NULL Pointer
You can create a NULL pointer to pass to library functions in the following ways:

• Pass an empty array [] as the argument.


• Use the libpointer function:
p = libpointer; % no arguments

p = libpointer('string') % string argument

p = libpointer('cstring') % pointer to a string argument


• Use the libstruct function:
p = libstruct('structtype'); % structure type

Empty libstruct Object

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

MATLAB displays the initialized values.

Manually Convert Data Passed to Functions


Under most conditions, MATLAB software automatically converts data passed to and from external
library functions to the type expected by the external function. However, you might choose to convert
your argument data manually. For example:

• 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

Shared Library shrlibsample


MATLAB includes a sample external library called shrlibsample. The library is in the folder
matlabroot\extern\examples\shrlib.

View the source code in MATLAB.

edit([matlabroot '/extern/examples/shrlib/shrlibsample.c'])
edit([matlabroot '/extern/examples/shrlib/shrlibsample.h'])

To use the shrlibsample library, choose one of the following.

• Add the folder to your MATLAB path:

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

Functions in library shrlibsample:

[double, doublePtr] addDoubleRef(double, doublePtr, double)


double addMixedTypes(int16, int32, double)
[double, c_structPtr] addStructByRef(c_structPtr)
double addStructFields(c_struct)
c_structPtrPtr allocateStruct(c_structPtrPtr)
voidPtr deallocateStruct(voidPtr)
lib.pointer exportedDoubleValue
lib.pointer getListOfStrings
doublePtr multDoubleArray(doublePtr, int32)
[lib.pointer, doublePtr] multDoubleRef(doublePtr)
int16Ptr multiplyShort(int16Ptr, int32)
doublePtr print2darray(doublePtr, int32)
printExportedDoubleValue
cstring readEnum(Enum1)
[cstring, cstring] stringToUpper(cstring)

6-17
6 Calling Functions in C Shared Libraries from MATLAB

Pass String Arguments Examples


In this section...
“stringToUpper Function” on page 6-18
“Convert MATLAB Character Array to Uppercase” on page 6-18

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.

EXPORTED_FUNCTION char* stringToUpper(char *input)


{
char *p = input;

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.

Return Type Name Arguments


[cstring, stringToUpper (cstring)
cstring]

Convert MATLAB Character Array to Uppercase


This example shows how to pass a MATLAB character array str to a C function, stringToUpper.

str = 'This was a Mixed Case string';

Load the library containing the stringToUpper function.

if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

Pass str to the function.

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

Pass Structures Examples


In this section...
“addStructFields and addStructByRef Functions” on page 6-20
“Add Values of Fields in Structure” on page 6-21
“Preconvert MATLAB Structure Before Adding Values” on page 6-21
“Autoconvert Structure Arguments” on page 6-22
“Pass Pointer to Structure” on page 6-22

addStructFields and addStructByRef Functions


The shrlibsample example library contains two functions with c_struct structure input
parameters. c_struct is defined in the shrlibsample.h header file.

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.

EXPORTED_FUNCTION double addStructFields(struct c_struct st)


{
double t = st.p1 + st.p2 + st.p3;
return t;
}

The MATLAB function signature is:

Return Type Name Arguments


double addStructFields (struct c_struct)

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.

EXPORTED_FUNCTION double addStructByRef(struct c_struct *st) {


double t = st->p1 + st->p2 + st->p3;
st->p1 = 5.5;
st->p2 = 1234;
st->p3 = 12345678;
return t;
}

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:

Return Type Name Arguments


[double, addStructByRef (c_structPtr)
c_structPtr]

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.

Add Values of Fields in Structure


This example shows how to pass a MATLAB structure to the function, addStructFields.

Create and initialize structure sm. Each field is of type double.


sm.p1 = 476;
sm.p2 = -299;
sm.p3 = 1000;

Load the library containing the addStructFields function.


if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

Call the function. MATLAB automatically converts the fields of structure sm to the library definition
for c_struct.
calllib('shrlibsample','addStructFields',sm)

ans = 1177

Preconvert MATLAB Structure Before Adding Values


This example shows how to preconvert structure sm to c_struct before calling addStructFields.
If you repeatedly pass sm to functions, preconverting eliminates the processing time required by
MATLAB to autoconvert the structure for each function call.

Create and initialize a MATLAB structure.


sm.p1 = 476;
sm.p2 = -299;
sm.p3 = 1000;

Load the library containing the addStructFields function.


if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

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);

Display the field names and values.

get(sc)

p1: 476
p2: -299
p3: 1000

Add the field values.

calllib('shrlibsample','addStructFields',sc)

ans = 1177

Autoconvert Structure Arguments


This example shows how to pass a MATLAB structure to a C library function, addStructByRef.
When you pass the structure, MATLAB automatically converts the field types, but MATLAB also
makes a copy of the fields.

Load the library.

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.

S = struct with fields:


p1: 476
p2: -299
p3: 1000

Pass Pointer to Structure


This example shows how calling the addStructByRef function with a pointer modifies the fields in
the input argument.

6-22
Pass Structures Examples

if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

Create a structure of type c_struct.

S.p1 = 20;
S.p2 = 99;
S.p3 = 3;

Create a pointer sp to the structure.

sp = libpointer('c_struct',S);
sp.Value

ans = struct with fields:


p1: 20
p2: 99
p3: 3

Pass the pointer to the function.

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

ans = struct with fields:


p1: 5.5000
p2: 1234
p3: 12345678

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

Pass Enumerated Types Examples


In this section...
“readEnum Function” on page 6-24
“Display Enumeration Values” on page 6-24

readEnum Function
The readEnum function in the shrlibsample library displays a string that matches the input
argument.

EXPORTED_FUNCTION char* readEnum(TEnum1 val)


{
static char outputs[][20] = {
{"You chose en1"},
{"You chose en2"},
{"You chose en4"},
{"enum not defined"},
{"ERROR"} };

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 function signature is:

Return Type Name Arguments


cstring readEnum (Enum1)

The values for the Enum1 input are defined in the shrlibsample.h header file.

typedef enum Enum1 {en1 = 1, en2, en4 = 4} TEnum1;

Display Enumeration Values


This example shows how to pass enumeration values to the readEnum function in the shrlibsample
library. Load the library.

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

Pass Pointers Examples


In this section...
“multDoubleRef Function” on page 6-26
“Pass Pointer of Type double” on page 6-26
“Create Pointer Offset from Existing lib.pointer Object” on page 6-27
“Multilevel Pointers” on page 6-27
“allocateStruct and deallocateStruct Functions” on page 6-27
“Pass Multilevel Pointer” on page 6-28
“Return Array of Strings” on page 6-28

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:

Return Type Name Arguments


[lib.pointer, multDoubleRef (doublePtr)
doublePtr]

Pass Pointer of Type double


This example shows how to construct and pass a pointer to C function multDoubleRef.

Load the library containing the function.


if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

Construct a pointer, Xptr, to the input argument, X.


X = 13.3;
Xptr = libpointer('doublePtr',X);

Verify the contents of Xptr.


get(Xptr)

Value: 13.3000
DataType: 'doublePtr'

Call the function and check the results.

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

Create Pointer Offset from Existing lib.pointer Object


This example shows how to create a pointer to a subset of a MATLAB vector X. The new pointer is
valid only as long as the original pointer exists.

Create a pointer to a vector.

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.

allocateStruct and deallocateStruct Functions


The allocateStruct function in the shrlibsample library takes a c_structPtrPtr argument.

6-27
6 Calling Functions in C Shared Libraries from MATLAB

EXPORTED_FUNCTION void allocateStruct(struct c_struct **val)


{
*val=(struct c_struct*) malloc(sizeof(struct c_struct));
(*val)->p1 = 12.4;
(*val)->p2 = 222;
(*val)->p3 = 333333;
}

The MATLAB function signatures are:

Return Type Name Arguments


c_structPtrPtr allocateStruct (c_structPtrPtr)
voidPtr deallocateStruct (voidPtr)

Pass Multilevel Pointer


This example shows how to pass a multilevel pointer to a C function.

Load the library containing allocateStruct and deallocateStruct.

if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

Create a c_structPtr pointer.

sp = libpointer('c_structPtr');

Call allocateStruct to allocate memory for the structure.

res = calllib('shrlibsample','allocateStruct',sp)

res = struct with fields:


p1: 12.4000
p2: 222
p3: 333333

Free the memory created by the allocateStruct function.

calllib('shrlibsample','deallocateStruct',sp)

Return Array of Strings


Suppose that you have a library, myLib, with a function, acquireString, that reads an array of
strings. The function signature is:

Return Type Name Arguments


char** acquireString (void)

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:

for index = 0:2


tempPtr = ptr + index;
tempPtr.Value
end

ans =
'str1'
ans =
'str2'
ans =
'str3'

See Also
libpointer

6-29
6 Calling Functions in C Shared Libraries from MATLAB

Pass Arrays Examples


In this section...
“print2darray Function” on page 6-30
“Convert MATLAB Array to C-Style Dimensions” on page 6-30
“multDoubleArray Function” on page 6-31
“Preserve 3-D MATLAB Array” on page 6-31

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");
}
}

Convert MATLAB Array to C-Style Dimensions


This example shows how to pass data stored columnwise in a MATLAB array to a C function that
assumes a row-by-column format.

Load the library containing the print2darray function.


if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

Create a MATLAB array with 4 rows and 3 columns.


m = reshape(1:12,4,3)

m = 4×3

1 5 9
2 6 10
3 7 11
4 8 12

Display the values. The first column is [1 4 7 10] instead of [1 2 3 4].


calllib('shrlibsample','print2darray',m,4)

6-30
Pass Arrays Examples

1 2 3
4 5 6
7 8 9
10 11 12

Transpose m to get the desired result.

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.

EXPORTED_FUNCTION void multDoubleArray(double *x,int size)


{
/* Multiple each element of the array by 3 */
int i;
for (i=0;i<size;i++)
*x++ *= 3;
}

The MATLAB function signature is:

Return Type Name Arguments


doublePtr multDoubleArray (doublePtr,
int32)

Preserve 3-D MATLAB Array


This example shows how a C function changes the dimensions of a MATLAB array, and how to restore
its shape.

Load the library.

if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

Create a 2-by-5-by-2 input array and display its dimensions.

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

Restore the original shape.

vout = reshape(vout,vs);
size(vout)

ans = 1×3

2 5 2

6-32
Iterate Through lib.pointer Object

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

Create Cell Array from lib.pointer Object


This example shows how to create a MATLAB® cell array of character vectors, mlStringArray,
from the output of the getListOfStrings function.

Load the shrlibsample library.

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.

% read until end of list (NULL)


while ischar(ptrindex.value{1})
mlStringArray{index} = ptrindex.value{1};
% increment pointer
ptrindex = ptrindex + 1;
% increment array index
index = index + 1;
end

View the contents of the cell array.

mlStringArray

mlStringArray = 1x4 cell


{'String 1'} {'String Two'} {0x0 char} {'Last string'}

6-33
6 Calling Functions in C Shared Libraries from MATLAB

Perform Pointer Arithmetic on Structure Array


This example shows how to use pointer arithmetic to access elements of a structure. The example
creates a MATLAB structure, based on the c_struct definition in the shrlibsample.h header file.

Load the definition.

if not(libisloaded('shrlibsample'))
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end

Create the MATLAB structure.

s = struct('p1',{1,2,3},'p2',{1.1,2.2,3.3},'p3',{0});

Create a pointer to the structure.

sptr = libpointer('c_struct',s);

Read the values of the first element.

v1 = sptr.Value

v1 = struct with fields:


p1: 1
p2: 1
p3: 0

Read the values of the next element by incrementing the pointer.

sptr = sptr + 1;
v2 = sptr.Value

v2 = struct with fields:


p1: 2
p2: 2
p3: 0

6-34
Represent Pointer Arguments in C Shared Library Functions

Represent Pointer Arguments in C Shared Library Functions


In this section...
“Pointer Arguments in C Functions” on page 6-35
“Put String into Void Pointer” on page 6-35
“Memory Allocation for External Library” on page 6-36

Pointer Arguments in C Functions


Many functions in external libraries pass arguments by reference. When you pass by reference, you
pass a pointer to the value. In the function signature, pointer arguments have names ending in Ptr
and PtrPtr. Although MATLAB does not support passing by reference, you can create a MATLAB
argument, called a lib.pointer object, that is compatible with a C pointer. This object is an instance of
the MATLAB lib.pointer class.

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.

• You want to modify the data in the input arguments.


• You are passing large amounts of data, and you want to control when MATLAB makes copies of the
data.
• The library stores and uses the pointer so you want the MATLAB function to control the lifetime of
the lib.pointer object.

Put String into Void Pointer


C represents characters as 8-bit integers. To use a MATLAB character array as an input argument,
convert the string to the proper type and create a voidPtr. For example:

str = 'string variable';


vp = libpointer('voidPtr',[int8(str) 0]);

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

Memory Allocation for External Library


In general, MATLAB passes a valid memory address each time you pass a variable to a library
function. Use a lib.pointer object in cases where the library stores the pointer and accesses the
buffer over time. In these cases, ensure that MATLAB has control over the lifetime of the buffer and
prevent copies of the data from being made. The following pseudo-code is an example of
asynchronous data acquisition that shows how to use a lib.pointer in this situation.

Suppose an external library myLib has the following functions:

AcquireData(int points,short *buffer)


IsAquisitionDone(void)

where buffer is declared as follows:

short buffer[99]

First, create a lib.pointer to an array of 99 points:

BufferSize = 99;
pBuffer = libpointer('int16Ptr',zeros(BufferSize,1));

Then, begin acquiring data and wait in a loop until it is done:

calllib('myLib','AcquireData,BufferSize,pbuffer)
while (~calllib('myLib','IsAcquisitionDone')
pause(0.1)
end

The following statement reads the data in the buffer:

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

Represent Structure Arguments in C Shared Library Functions

Structure Argument Requirements


When you pass a MATLAB structure to an external library function:

• 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.

Find Structure Field Names


To determine the name and data type of structure fields, you can:

• Consult the library documentation.


• Look at the structure definition in the library header file.
• Use the libstruct function.

Strategies for Passing Structures


MATLAB automatically converts a structure to the library definition for that structure type. For most
cases, such as working with small structures, this works fine.

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

Explore libstruct Objects


This example shows how to display information about and modify a libstruct object, c_struct.

Load the shrlibsample library containing the c_struct definition.

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 structure field values.

set(sc,'p1',100,'p2',150,'p3',200)

Display field values.

get(sc)

p1: 100
p2: 150
p3: 200

Modify values using MATLAB field structure syntax.

sc.p1 = 23;
get(sc)

p1: 23
p2: 150
p3: 200

6-38
MATLAB Prototype Files

MATLAB Prototype Files


In this section...
“When to Use Prototype Files” on page 6-39
“How to Create Prototype Files” on page 6-39
“How to Specify Thunk Files” on page 6-39
“Deploy Applications That Use loadlibrary” on page 6-39
“loadlibrary in Parallel Computing Environment” on page 6-40
“Change Function Signature” on page 6-40
“Rename Library Function” on page 6-40
“Load Subset of Functions in Library” on page 6-40
“Call Function with Variable Number of Arguments” on page 6-40

When to Use Prototype Files


MATLAB provides a way to modify header file information by creating a prototype file, a file of
MATLAB commands.

Like a header file, the prototype file contains the function signatures for the library. Here are some
reasons for using a prototype file.

• To deploy applications that use loadlibrary (using MATLAB Compiler™).


• To use loadlibrary in a parallel computing environment (using Parallel Computing Toolbox™).
• To change signatures of the library functions.
• To rename some of the library functions.
• To use only a small percentage of the functions in the library you are loading.
• To use functions with a variable number of arguments.

You can change the prototypes by editing the prototype file and reloading the library.

How to Create Prototype Files


To create a prototype file, use the mfilename option of the loadlibrary function.

How to Specify Thunk Files


For information about default thunk file names, see loadlibrary. To change the name, use the
thunkfilename option.

Deploy Applications That Use loadlibrary


To deploy a MATLAB application that uses loadlibrary, using MATLAB Compiler:

• Create a prototype file.


• For 64-bit applications, specify a thunk file.

6-39
6 Calling Functions in C Shared Libraries from MATLAB

• Include all the relevant files when creating the project with mcc.

loadlibrary in Parallel Computing Environment


To use loadlibrary in a parallel computing environment (using Parallel Computing Toolbox):

• Create a prototype file.


• For 64-bit applications, specify a thunk file.
• Make sure that all relevant files are accessible to all workers.

Change Function Signature


Edit the prototype file, changing the fcns.LHS or fcns.RHS field for that function. This edit changes
the types of arguments on the left-hand side or right-hand side, respectively.

Rename Library Function


Edit the prototype file, defining the fcns.alias field for that function.

Load Subset of Functions in Library


Edit the prototype file, commenting out the unused functions. This edit reduces the amount of
memory required for the library.

Call Function with Variable Number of Arguments


Create an alias function in a prototype file for each set of arguments you use to call the function.

6-40
7

Intro to MEX-Files
7 Intro to MEX-Files

Choosing MEX Applications


You can call your own C, C++, or Fortran programs from the MATLAB command line as if they were
built-in functions. These programs are called MEX functions. MEX functions are not appropriate for
all applications. MATLAB is a high-productivity environment whose specialty is eliminating time-
consuming, low-level programming in compiled languages like C or C++. In general, do your
programming in MATLAB. Do not use MEX files unless your application requires it.

To create a MEX function, write your program using MATLAB APIs, then build it using the mex
command. The APIs provide these features:

• Call MATLAB functions from the MEX function.


• Integrate seamlessly into MATLAB, getting inputs from and returning results to MATLAB.
• Support MATLAB data types.

C++ MEX Functions


As of MATLAB R2018a, write your C++ MEX functions using these APIs, which support C++11
programming features. These APIs, based on the matlab::data::Array class, provide better type
safety, array bounds checking, and support for modern C++ constructs to simplify coding.

• “C++ MEX API” on page 9-11


• “MATLAB Data API”

For more information, see “C++ MEX Applications”.

C/C++ MEX Functions for MATLAB R2017b and Earlier


If your MEX functions must run in MATLAB R2017b or earlier, or if you prefer to work in the C
language, then write your source files using functions in these libraries based on the mxArray data
structure.

• C MEX API on “C MEX File Applications”


• “C Matrix API”

For more information, see “C MEX File Applications”.

Caution Do not mix functions in the C Matrix API with functions in the MATLAB Data API.

Fortran MEX Functions


To write Fortran MEX functions, use these APIs based on the mxArray data structure.

• “Fortran MEX API”


• “Fortran Matrix API”

For more information, see “Fortran MEX File Applications”.

7-2
Choosing MEX Applications

MEX Terms
MEX stands for MATLAB executable and has different meanings, as shown in this table.

MEX Term Definition


source MEX file C, C++, or Fortran source code file.
binary MEX file or MEX Dynamically linked subroutine executed in the MATLAB environment.
function
MEX API Functions in the C MEX API and Fortran MEX API to perform operations
in the MATLAB environment.
mex build script MATLAB function to create a binary file from a source file.

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

MEX File Placement


Put your MEX files in a folder on the MATLAB path. Alternatively, run MATLAB from the folder
containing the MEX file. MATLAB runs functions in the current working folder before functions on the
path.

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.

MEX Files on Windows Network Drives


Windows network drive file servers do not always report folder and file changes correctly. If you
change a MEX file on a network drive and MATLAB does not use the latest changes, change folders
away from and then back to the folder containing the file.

See Also
path | addpath

7-4
Use Help Files with MEX Functions

Use Help Files with MEX Functions


You can document the behavior of your MEX functions by writing a MATLAB script containing
comment lines. The help command searches for a MATLAB script and displays the appropriate text.

For example, copy the following text from the arrayProduct.c MEX source file into a file,
arrayproduct.m.

% arrayproduct.m Help file for arrayProduct MEX-file.


% arrayProduct.c - example in MATLAB External Interfaces
%
% Multiplies an input scalar (multiplier)
% times a 1xN matrix (inMatrix)
% and outputs a 1xN matrix (outMatrix)
%
% The calling syntax is:
%
% outMatrix = arrayProduct(multiplier, inMatrix)
%

% This is a MEX-file for MATLAB.


% Copyright 2007-2014 The MathWorks, Inc.
%

When you type:

help arrayproduct

MATLAB displays the comments.

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

The MATLAB Array


The MATLAB language works with a single object type: the MATLAB array. All MATLAB variables
(including scalars, vectors, matrices, character arrays, cell arrays, structures, and objects) are stored
as MATLAB arrays. In C/C++, the MATLAB array is declared to be of type mxArray. The mxArray
structure contains the following information about the array:

• 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.

Input Argument prhs

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.

Output Argument plhs

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.

For example, given the matrix:


a = ['house'; 'floor'; 'porch']

a =
house
floor
porch

its dimensions are:


size(a)

ans =
3 5

and its data is stored as:

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.

MATLAB Data Types


Complex Double-Precision Matrices

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.

Other Numeric Matrices

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

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.

Using Data Types


You can write source MEX files, MAT-file applications, and engine applications in C/C++ that accept
any class or data type supported by MATLAB (see “Data Types”). In Fortran, only the creation of
double-precision n-by-m arrays and strings are supported. You use binary C/C++ and Fortran MEX
files like MATLAB functions.

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

Declaring Data Structures

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:

myData = mxCreateDoubleMatrix(m, 1, mxREAL);

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')

Use the mex command to build the MEX file.

mex explore.c -R2018a

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

Testing for Most-Derived Class


If you define functions that require inputs that are:

• MATLAB built-in types


• Not subclasses of MATLAB built-in types

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.

The following code tests an input argument, inputArg:


if strcmp(class(inputArg),'single')
% Call function
else
inputArg = single(inputArg);
end

Testing for a Category of Types


Suppose that you create a MEX function, myMexFcn, that requires two numeric inputs that must be of
type double or single:
outArray = myMexFcn(a,b)

Define a cell array floatTypes that contains the words double and single:
floatTypes = {'double','single'};

% Test for proper types


if any(strcmp(class(a),floatTypes)) && ...
any(strcmp(class(b),floatTypes))
outArray = myMexFcn(a,b);
else
% Try to convert inputs to avoid error
...
end

Another Test for Built-In Types


You can use isobject to separate built-in types from subclasses of built-in types. The isobject
function returns false for instances of built-in types. For example:
% Create a int16 array
a = int16([2,5,7,11]);
isobject(a)

ans =
0

Determine if an array is one of the built-in integer types:


if isa(a,'integer') && ~isobject(a)
% a is a built-in integer type

7-12
Testing for Most-Derived Class

...
end

7-13
7 Intro to MEX-Files

Build C MEX Function


This example shows how to build the example C MEX function arrayProduct. Use this example to
verify the C build configuration for your system. For information about building C++ MEX functions,
see “Build C++ MEX Programs” on page 9-8.

Verify that you have installed a Supported and Compatible Compilers. For information about
installing a compiler, visit the vendor website.

mex -setup C

Copy the source MEX file to a writable folder on your path.

copyfile(fullfile(matlabroot,'extern','examples','mex','arrayProduct.c'),'.','f')

Call the mex command to build the function.

mex arrayProduct.c -R2018a

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

Change Default Compiler

To Change Default on Windows Systems


MATLAB maintains separate default compiler options for C, C++, and Fortran language files. If you
have multiple compilers that MATLAB supports for a language installed on your Windows system,
then MATLAB selects one as the default compiler. To change the default, use the mex -setup lang
command. MATLAB displays a message with links to select a different 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

To change the default C compiler, at the MATLAB command prompt, type:

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

To change the default C++ compiler, type:

mex -setup cpp

For an example, see “Choose a C++ Compiler” on page 8-19.

Fortran Compilers

To change the default Fortran compiler, type:

mex -setup Fortran

To Change Default on Linux Systems


For information about changing the gcc/g++ compiler to a supported version on Linux platforms, see
“Change Default gcc Compiler on Linux System” on page 7-17.

7-15
7 Intro to MEX-Files

To Change Default on macOS Systems


If you have multiple versions of Xcode installed on your system, MATLAB uses the compiler defined
by the Xcode.app application. You can use the compiler from an Xcode.X.app, where
Xcode.X.app is the name you used to save a previously installed Xcode version.

Before starting MATLAB, from the Terminal type:

xcode-select -switch /Applications/Xcode.X.app/Contents/Developer

To see which Xcode MATLAB is using, at the Terminal type:

xcode-select -p

Do Not Use mex -f optionsfile Syntax


The mex command -f option to specify a build configuration file will be removed in a future release.
Instead, use the workflows described in this topic for specifying a compiler.

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

Change Default gcc Compiler on Linux System


MATLAB supports only one compiler for each language on Linux platforms. If you have multiple
compilers installed, the default compiler might not be a compiler that MATLAB supports. To
determine the default gcc compiler for your system, in MATLAB, type:

!which gcc

To change the default compiler, choose one of these options.

• 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

Custom Build with MEX Script Options


The mex build script is sufficient for building MEX files. Following are reasons that you might need
more detailed information:

• 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

Call LAPACK and BLAS Functions


You can call a LAPACK or BLAS function using a MEX file. To create a MEX file, you need C/C++ or
Fortran programming experience and the software resources (compilers and linkers) to build an
executable file. It also is helpful to understand how to use Fortran subroutines. MATLAB provides the
mwlapack and mwblas libraries in matlabroot/extern/lib. To help you get started, there are
source code examples in matlabroot/extern/examples/refbook.

To call LAPACK or BLAS functions:

1 Create a source MEX file containing the mexFunction gateway routine.


2 Make sure that you have a supported compiler for your platform. For an up-to-date list of
supported compilers, see Supported and Compatible Compilers.
3 Build a binary MEX file using the mex command and the separate complex build flag -R2017b.

• 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/.

Build matrixMultiply MEX Function Using BLAS Functions


This example shows how to build the example MEX file matrixMultiply.c, which uses functions
from the BLAS library. To work with this file, copy it to a local folder. For example:

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')

To build the MEX file, type:

mex -v -R2017b matrixMultiply.c -lmwblas

To run the MEX file, type:

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

Preserve Input Values from Modification


Many LAPACK and BLAS functions modify the values of arguments passed to them. It is good practice
to make a copy of arguments you can modify before passing them to these functions. For information

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 build the file, type:

mex -v -R2017b matrixDivide.c -lmwlapack

To test, type:

A = [1 2; 3 4];
B = [5; 6];
X = matrixDivide(A,B)

X =
-4.0000
4.5000

Pass Arguments to Fortran Functions from C/C++ Programs


The LAPACK and BLAS functions are written in Fortran. C/C++ and Fortran use different conventions
for passing arguments to and from functions. Fortran functions pass arguments by reference, while
C/C++ functions pass arguments by value. When you pass by value, you pass a copy of the value.
When you pass by reference, you pass a pointer to the value. A reference is also the address of the
value.

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.

/* pointers to input & output matrices*/


double *A, *B, *C;
/* matrix dimensions */
mwSignedIndex m,n,p;
/* other inputs to dgemm */
char *chn = "N";
double one = 1.0, zero = 0.0;

/* call BLAS function */


dgemm(chn, chn, &m, &n, &p, &one, A, &m, B, &p, &zero, C, &m);

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.

Pass Arguments to Fortran Functions from Fortran Programs


You can call LAPACK and BLAS functions from Fortran MEX files. The following example takes two
matrices and multiplies them by calling the BLAS routine dgemm. To run the example, copy the code
into the editor and name the file calldgemm.F.

#include "fintrf.h"

subroutine mexFunction(nlhs, plhs, nrhs, prhs)


mwPointer plhs(*), prhs(*)
integer nlhs, nrhs
mwPointer mxcreatedoublematrix
mwPointer mxgetpr
mwPointer A, B, C
mwSize mxgetm, mxgetn
mwSignedIndex m, n, p
mwSize numel
double precision one, zero, ar, br
character ch1, ch2

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))

plhs(1) = mxcreatedoublematrix(m, n, 0.0)


C = mxgetpr(plhs(1))
numel = 1
call mxcopyptrtoreal8(A, ar, numel)
call mxcopyptrtoreal8(B, br, numel)

call dgemm(ch1, ch2, m, n, p, one, %val(A), m,


+ %val(B), p, zero, %val(C), m)

return
end

Link to the BLAS library, which contains the dgemm function.

mex -v -R2017b calldgemm.F -lmwblas

7-21
7 Intro to MEX-Files

Modify Function Name on UNIX Systems


Add an underscore character following the function name when calling LAPACK or BLAS functions on
a UNIX system. For example, to call dgemm, use:

dgemm_(arg1, arg2, ..., argn);

Or add these lines to your source code:

#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

Pass Separate Complex Numbers to Fortran Functions


MATLAB stores complex numbers the same way as Fortran, in one vector, pa, with the real and
imaginary parts interleaved.

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.

• mat2fort — Convert MATLAB separate complex matrix to Fortran complex storage.


• fort2mat — Convert Fortran complex storage to MATLAB separate real and imaginary parts.

To use these routines:

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.

Handling Complex Number Input Values


It is unnecessary to copy arguments for functions that use complex number input values. The
mat2fort conversion routine creates a copy of the arguments for you. For information, see “Preserve
Input Values from Modification” on page 7-19.

Handling Complex Number Output Arguments


For complex variables returned by a Fortran function, do the following:

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.

Pass Complex Variables — matrixDivideComplex


This example shows how to call a function, passing complex prhs[0] as input and receiving complex
plhs[0] as output. Temporary variables zin and zout contain the input and output values in
Fortran format. To see the example, open matrixDivideComplex.c in the MATLAB Editor. To
create the MEX file, copy the source file to a writable folder.

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');

Build the MEX function.


mex('-v','-R2017b',['-I' fortheaderdir],'matrixDivideComplex.c',fortfile,'-lmwlapack')

Test the function.

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

Handle Fortran Complex Return Type — dotProductComplex


Some level 1 BLAS functions (for example, zdotu and zdotc) return a double complex type, which
the C language does not support. The following C MEX file, dotProductComplex.c, shows how to
handle the Fortran complex return type for function zdotu. To see the example, open
dotProductComplex.c in the MATLAB Editor.

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.

For example, to build:

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

Symmetric Indefinite Factorization Using LAPACK — utdu_slv


The example utdu_slv.c calls LAPACK functions zhesvx and dsysvx. To see the example, open
utdu_slv.c in the MATLAB Editor. To create the MEX file, copy the source file to a writable folder.

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

MATLAB Support for Interleaved Complex API in MEX Functions


When a matrix of complex numbers is represented in computer memory, there are several choices for
the location and order of storage. Before MATLAB Version 9.4 (R2018a), MATLAB used a separate
storage representation. The real and the imaginary parts of the numbers were stored separately.
MATLAB uses an interleaved storage representation for C and Fortran language MEX files, where the
real and imaginary parts are stored together. Interleaved complex refers to this representation.

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.

Separate Complex API and Interleaved Complex API


There are two versions of the C Matrix API and “Fortran Matrix API”.

• 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.

Matrix API Changes Supporting Interleaved Complex


The following changes to the C and Fortran Matrix APIs support interleaved complex.

• 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:

• mxMakeArrayComplex (C) and mxMakeArrayComplex (Fortran)


• mxMakeArrayReal (C) and mxMakeArrayReal (Fortran)
• Matrix API functions not supported in the -R2018a API:

• mxGetPi (C) and mxGetPi (Fortran)


• mxGetImagData (C) and mxGetImagData (Fortran)
• mxSetPi (C) and mxSetPi (Fortran)

7-27
7 Intro to MEX-Files

• mxSetImagData (C) and mxSetImagData (Fortran)


• The behavior of these Matrix API functions changes in the -R2018a API. In addition, these
functions are to be phased out.

• mxGetPr (C) and mxGetPr (Fortran)


• mxSetPr (C) and mxSetPr (Fortran)
• The behavior of these Matrix API functions changes in the -R2018a API:

• mxGetData (C) and mxGetData (Fortran)


• mxSetData (C) and mxSetData (Fortran)
• mxGetElementSize (C) and mxGetElementSize (Fortran)
• The behavior of these Fortran Matrix API functions changes in the -R2018a API:

• mxCopyComplex16ToPtr (Fortran)
• mxCopyPtrToComplex16 (Fortran)
• mxCopyComplex8ToPtr (Fortran)
• mxCopyPtrToComplex8 (Fortran)

Writing MEX Functions with Interleaved Complex API


To learn how to write MEX functions using the interleaved complex API, see “Handle Complex Data in
C MEX File” on page 8-30 in C applications or “Handle Complex Fortran Data” on page 10-22.

MEX Functions Created in MATLAB R2017b and Earlier


If you already build MEX functions, MEX S-functions, or standalone MATLAB engine and MAT-file
applications, then you should review the “Do I Need to Upgrade My MEX Files to Use Interleaved
Complex API?” on page 7-36 topic. To help transition your MEX files and S-functions to the
interleaved complex API, MATLAB maintains a compatibility interface. To build MEX files with the
compatibility interface, use the mex -R2017b flag. If your code processes complex numbers, you
might notice a performance impact as MATLAB adapts your data to the interleaved complex format.

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

Upgrade MEX Files to Use Interleaved Complex API


This topic describes how to upgrade your MEX files to use the interleaved complex API. You can
continue to use the separate complex API by calling the mex command with the -R2017b option.
However, for more information about using this option, see “Do I Need to Upgrade My MEX Files to
Use Interleaved Complex API?” on page 7-36

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.

To update your MEX source code, use the following checklist.

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.

Back up all source, binary, and test files.


3 Iteratively refactor your existing code by checking for the following conditions.

a “Check Array Complexity Using mxIsComplex” on page 7-30


b “Add MX_HAS_INTERLEAVED_COMPLEX to Support Both Complex Number
Representations” on page 7-30
c “Use Typed Data Access Functions” on page 7-31
d “Handle Complex mxArrays” on page 7-32
e “Replace Separate Complex Functions” on page 7-34
f “Calculate Array Data Size with mxGetElementSize” on page 7-34
g “Consider Replacing To-Be-Phased-Out Functions” on page 7-34
4 After each change, compile using the interleaved complex API. To build myMexFile.c, type:

mex -R2018a myMexFile.c

To build myMexFile.F, type:

mex -R2018a myMexFile.F


5 Resolve failures and warnings.
6 Test after each refactoring.

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

Check Array Complexity Using mxIsComplex


If your code calls the mxGetPi function to determine if an array has complex elements, use the
mxIsComplex function instead. This function builds with both the -R2017b and -R2018a APIs.
Search your code for the following patterns.

Replace C Source Code: With:


mxArray *pa; mxArray *pa;
... ...
if (mxGetPi(pa)) { if (mxIsComplex(pa)) {
/* process complex array */ /* process complex array */
} }
double *ptr;
ptr = mxGetPi(pa);
if (ptr != NULL) {
/* process complex array */
}

Add MX_HAS_INTERLEAVED_COMPLEX to Support Both Complex


Number Representations
To write code that builds with both the -R2017b and -R2018a APIs, add the
MX_HAS_INTERLEAVED_COMPLEX macro. This macro returns true if you build the MEX file with the
-R2018a option.

Wrapping the following code in an #if MX_HAS_INTERLEAVED_COMPLEX statement ensures that


this code will build with either the -R2017b or -R2018a mex option. However, in this example, there
is no code to execute when built with -R2018a.

7-30
Upgrade MEX Files to Use Interleaved Complex API

Replace C Source Code: With:


static void static void
analyze_double(const mxArray *array_ptr) analyze_double(const mxArray *array_ptr)
{ {
mwSize total_num_of_elements, index; mwSize total_num_of_elements, index;
double *pr, *pi; total_num_of_elements = mxGetNumberOfElements(arr
total_num_of_elements = mxGetNumberOfElements(array_ptr);
pr = mxGetPr(array_ptr); #if MX_HAS_INTERLEAVED_COMPLEX
pi = mxGetPi(array_ptr); /* interleaved complex API processing */
for (index=0; index<total_num_of_elements; index++) {
mxComplexDouble *pc;
if (mxIsComplex(array_ptr)) { mxDouble *p;
mexPrintf("%g + %gi\n", *pr++, *pi++); if (mxIsComplex(array_ptr)) {
} pc = mxGetComplexDoubles(array_ptr);
else { for (index=0; index<total_num_of_elements
mexPrintf("%g\n", *pr++); mexPrintf(" = %g + %gi\n",(*pc).real,
} pc++;
} }
} }
else {
p = mxGetDoubles(array_ptr);
for (index=0; index<total_num_of_elements
mexPrintf(" = %g\n", *p++);
}
}
#else
/* separate complex API processing */
double *pr, *pi;
pr = mxGetPr(array_ptr);
pi = mxGetPi(array_ptr);
for (index=0; index<total_num_of_elements; in
if (mxIsComplex(array_ptr)) {
mexPrintf("%g + %gi\n", *pr++, *pi++)
}
else {
mexPrintf("%g\n", *pr++);
}
}
#endif
}

Replace Fortran Source Code: With:


mwPointer prhs(*), pr mwPointer prhs(*), pr
pr = mxGetPr(prhs(1)) #if MX_HAS_INTERLEAVED_COMPLEX
pr = mxGetDoubles(prhs(1))
#else
pr = mxGetPr(prhs(1))
#endif

Use Typed Data Access Functions


To use the mxGetData and mxGetImagData functions, you must verify the type of the input mxArray
and manually cast the pointer output to the correct type. The typed data access functions verify the
type of the array and return the correct pointer type. When you use the mxGetInt16s and
mxGetComplexInt16s functions in the following code to process an int16 array, you do not need to
remember the corresponding C type, short int.

7-31
7 Intro to MEX-Files

Replace C Source Code: With:


static void static void
analyze_int16(const mxArray *array_ptr) analyze_int16(const mxArray *array_ptr)
{ {
short int *pr, *pi; mxComplexInt16 *pc;
pr = (short int *)mxGetData(array_ptr); mxInt16 *p;
pi = (short int *)mxGetImagData(array_ptr); if(mxIsComplex(array_ptr)) {
pc = mxGetComplexInt16s(array_ptr);
if (mxIsComplex(array_ptr)) { /* process complex data (*pc).real,(*pc).imag
/* process complex data *pr,*pi */ }
} }
else { else {
/* process real data *pr */ p = mxGetInt16s(array_ptr);
} /* process real data *p */
} }
}
}

Handle Complex mxArrays


The following examples show how MATLAB uses one array variable to represent a complex array.

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.

Replace C Source Code: With:


double *xr, *xi, *yr, *yi, *zr, *zi; /* get pointers to the complex arrays */
mxComplexDouble * xc = mxGetComplexDoubles(x);
/* get pointers to the real and imaginary parts of the
mxComplexDouble *arrays */
yc = mxGetComplexDoubles(y);
xr = mxGetPr(x); mxComplexDouble * zc = mxGetComplexDoubles(z);
xi = mxGetPi(x); ...
yr = mxGetPr(y); /* perform addition on element i */
yi = mxGetPi(y); zc[i].real = xc[i].real + yc[i].real;
zc[i].imag = xc[i].imag + yc[i].imag;
zr = mxGetPr(z);
zi = mxGetPi(z);

...
/* 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

Replace C Source Code: With:


mxGetPr(plhs[0])[0] = mxGetPr(prhs[0])[index];
if (mxIsComplex(prhs[0])) {
mxGetComplexDoubles(plhs[0])[0] = mxGetComplexDoubles(prhs[0])[index];
if (mxIsComplex(prhs[0])) { }
mxGetPi(plhs[0])[0] = mxGetPi(prhs[0])[index];
else {
mxGetDoubles(plhs[0])[0] = mxGetDoubles(prhs[0])[index];
} }

Complex Fortran mxArrays

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.

complex*16 x(*), y(*)

Instead of separately converting the real and imaginary parts of each mxArray, use the
mxGetComplexDoubles function.

Replace Fortran Source Code: With:


mwPointer mxGetPr, mxGetPi mwPointer mxGetComplexDoubles
integer*4 status
C Copy the data into native COMPLEX Fortran arrays.
integer*4 mxCopyPtrToComplex16, mxCopyComplex16
call mxCopyPtrToComplex16(
+ mxGetPr(prhs(1)), C Copy the data into native COMPLEX Fortran array
+ mxGetPi(prhs(1)),x,nx) status =
call mxCopyPtrToComplex16( + mxCopyPtrToComplex16(mxGetComplexDoubles(prh
+ mxGetPr(prhs(2)), C Test status for error conditions
+ mxGetPi(prhs(2)),y,ny)
status =
+ mxCopyPtrToComplex16(mxGetComplexDoubles(prh
C Test status for error conditions

Maintain Complexity of mxArray


This C code snippet shows how to convert a real, double, input array prhs[0] into a complex array.
The following code sets up the variables used to fill the complex part of the array with consecutive
numbers.

// code to check number of arguments and expected types


mwSize rows = mxGetM(prhs[0]);
mwSize cols = mxGetN(prhs[0]);
mwSize sz = mxGetElementSize(prhs[0]);

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).

Replace C Source Code: With:


plhs[0] = mxDuplicateArray(prhs[0]); plhs[0] = mxDuplicateArray(prhs[0]);

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

Replace Separate Complex Functions


The following functions are not in the interleaved complex API. You must replace them with
interleaved complex functions when handling complex data.

• 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.

Replace C Source Code: With:


mxArray *pa; mxArray *pa;
mwSize numElements; mwSize numElements;

int64_T *pr, *pi; mxComplexInt64 *pc;


pr = (int64_T *)mxGetData(pa); pc = mxGetComplexInt64s(pa);
pi = (int64_T *)mxGetImagData(pa); numElements = mxGetNumberOfElements(pa);
numElements = mxGetNumberOfElements(pa);

Calculate Array Data Size with mxGetElementSize


In the -R2018a API, the mxGetElementSize (C) function returns sizeof(std::complex<T>)
for a complex mxArray with data type T. This value is twice the value returned by the function in the
-R2017b API. Similarly, mxGetElementSize (Fortran) in the -R2018a API returns twice the
value as the function in the -R2017b API.

Consider Replacing To-Be-Phased-Out Functions


The following functions are in both the -R2017b and the -R2018a APIs. While you do not need
replace them with typed data access functions, the typed data functions provide type checking. Also,
if you use mxGetPr, you might choose mxGetPi for any complex array processing. This code pattern
causes errors when writing -R2018a MEX functions.

• 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

Replace C Source Code: With:


double *y; mxDouble *p;
/* create a pointer y to input matrix */ p = mxGetDoubles(prhs[1]);
y = mxGetPr(prhs[1]);

Replace Fortran Source Code: With:


mwPointer pr mwPointer pr
mwPointer mxGetPr mwPointer mxGetDoubles
C Create a pointer to input matrix
pr = mxGetPr(prhs(1)) pr = mxGetDoubles(prhs(1))

Add Build Information to MEX Help File


Consider creating a help file, described in “Use Help Files with MEX Functions” on page 7-5, that
contains build information. For example, create a file displayTypesafeNumeric.m containing the
following text.
% displayTypesafeNumeric.m Help file for displayTypesafeNumeric C MEX function
%
% Use the following command to build this MEX file:
% mex -R2018a displayTypesafeNumeric.c

At the MATLAB command prompt, type:

help displayTypesafeNumeric
displayTypesafeNumeric.m Help file for displayTypesafeNumeric C MEX function

Use the following command to build this MEX file:


mex -R2018a displayTypesafeNumeric.c

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

Do I Need to Upgrade My MEX Files to Use Interleaved


Complex API?
You do not need to update your MEX source code to continue to build your MEX files. 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.

Can I Run Existing MEX Functions?


You can run existing binary MEX files without upgrading the files for use with the interleaved
complex API. However, other incompatibilities might prevent execution of an existing MEX function.
If your function does not execute properly, search for mex in the relevant MATLAB release notes and
review the Compatibility Considerations topics.

Must I Update My Source MEX Files?


State of Your Source Code Next Action
My MEX functions do not use complex numbers. Check that your functions properly handle any
complex data input. Calls to the mxGetPr (C)/
mxGetPr (Fortran) and mxGetData (C)/
mxGetData (Fortran) are not recommended
for complex arrays.

MathWorks recommends that you update your


code to use the MX_HAS_INTERLEAVED_COMPLEX
macro or build using the mex -R2017b option to
ensure the desired behavior across versions of
MATLAB.

If you use mxGetData or mxSetData, consider


replacing them with typed data access functions.
For more information, see Using the interleaved
complex API.
I do not plan to update my code. If your MEX functions use complex numbers, then
you have chosen to opt out. MathWorks
recommends that you build using the
compatibility flag -R2017b.

If your code processes complex numbers, you


might notice a performance impact as MATLAB
accesses the compatibility interface.
I want to update my code. Where do I start? To update source code, see “Upgrade MEX Files
to Use Interleaved Complex API” on page 7-29.
I use complex numbers in MEX functions, but do Ask the owner of the source code to follow the
not have access to the source code. steps in “Upgrade MEX Files to Use Interleaved
Complex API” on page 7-29.

7-36
Do I Need to Upgrade My MEX Files to Use Interleaved Complex API?

State of Your Source Code Next Action


I use complex numbers with third-party libraries. Identify the library's representation of complex
My MEX code is responsible for transforming the numbers. Sometimes the representation might be
MATLAB representation of complex numbers to closer to the interleaved representation used in
the library's representation of complex numbers. MATLAB.

In other cases, libraries have options for


representing complex numbers in memory. If this
is so, refer to the vendor documentation and
choose the representation that most closely
matches the MATLAB interleaved representation.
My MEX function generates errors. You must recompile the MEX file from the source
code. If using the -R2017b flag does not resolve
the issue, then there might be incompatibilities in
your source code. For information about
incompatibilities, see “Can I Run Existing MEX
Functions?” on page 7-36 MathWorks
recommends that you update your MEX source
code to use the 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

Troubleshooting MEX API Incompatibilities

File Is Not A MEX File


For more information, see “MEX Platform Compatibility” on page 7-54.

MEX File Compiled With Incompatible Options


When you build object files into a MEX function, make sure they are built with the same version of
the C or Fortran Matrix API.

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 -c function1.c -largeArrayDims


mex -c function2.c -R2018a
mex function1.o function2.o

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.

mex -c function1.c -largeArrayDims


mex function1.o -R2018a

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 -R2017b

Use this command instead.

mex function.cpp

Custom-built MEX File Not Supported In Current Release


MATLAB does not find a version number in the MEX file. The MEX file uses functions in an API that
requires a version number. For more information, see https://www.mathworks.com/matlabcentral/
answers/377799-compiling-mex-files-without-the-mex-command.

MEX File Is Compiled With Outdated Option


Your source code is compatible with the interleaved complex API. For best results, replace the mex -
largeArrayDims build option with the -R2018a option.

7-38
Troubleshooting MEX API Incompatibilities

MEX File Calls An Untyped Data Access Function


For more information, see “Typed Data Access in C MEX Files” on page 8-45.

MEX File Calls A 32-bit Function


For more information, see “Upgrade MEX Files to Use 64-Bit API” on page 7-40.

MEX File Does Not Contain An Entry Point


For more information, see “MEX Platform Compatibility” on page 7-54.

MEX File Built In MATLAB Release Not Supported In Current Release


For more information, see “MEX Version Compatibility” on page 7-59.

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

Upgrade MEX Files to Use 64-Bit API


The mex command uses the -largeArrayDims option by default. This topic describes how to
upgrade your MEX files to use the 64-bit API.

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.

After each change, build and test your code:

• Build with the 32-bit API. For example, to build myMexFile.c, type:

mex -compatibleArrayDims myMexFile.c


• Test after each refactoring — see “Test, Debug, and Resolve Differences After Each
Refactoring Iteration” on page 7-43.
3 Compile using the 64-bit API. 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