MATLAB® Compiler 4 User’s Guide
How to Contact The MathWorks Web Newsgroup www.mathworks.com/contact_TS.html Technical Support www.mathworks.com comp.soft-sys.matlab suggest@mathworks.com bugs@mathworks.com doc@mathworks.com service@mathworks.com info@mathworks.com Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information 508-647-7000 (Phone) 508-647-7001 (Fax) The MathWorks, Inc.
Revision History September 1995 March 1997 January 1998 January 1999 September 2000 October 2001 July 2002 June 2004 August 2004 October 2004 November 2004 March 2005 September 2005 March 2006 September 2006 March 2007 September 2007 First printing Second printing Third printing Fourth printing Fifth printing Online only Sixth printing Online only Online only Online only Online only Online only Online only Online only Online only Online only Seventh printing Revised for Version 1.2 Revised for Version 2.
Contents Getting Started 1 What Is MATLAB Compiler? . . . . . . . . . . . . . . . . . . . . . . . Overview of MATLAB Compiler . . . . . . . . . . . . . . . . . . . . . . What Is the Deployment Tool? . . . . . . . . . . . . . . . . . . . . . . 1-2 1-2 1-2 How Does MATLAB Compiler Work? . . . . . . . . . . . . . . . . . MATLAB Compiler Generated Application or Library . . . . Wrapper Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Component Technology File (CTF) . . . . . . .
Installation and Configuration 2 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Supported Third-Party Compilers . . . . . . . . . . . . . . . . . . . . 2-2 2-2 2-2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Installing MATLAB Compiler . . . . . . . . . . . . . . . . . . . . . . . Installing an ANSI C or C++ Compiler . . . . . . . . . . . .
Deployment Process 4 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 Deploying to Programmers . . . . . . . . . . . . . . . . . . . . . . . . . Steps by the Programmer to Deploy to Programmers . . . . What Software Does a Programmer Need? . . . . . . . . . . . . . 4-3 4-3 4-4 Deploying to End Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . Steps by the Programmer to Deploy to End Users . . . . . . . What Software Does the End User Need? . . .
viii Contents Combining Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Conflicting Options on the Command Line . . . . . . . . . . . . . Using File Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 5-3 5-3 Using Macros to Simplify Compilation . . . . . . . . . . . . . . . Macro Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Understanding a Macro Option . . . . . . . . . . . . . . . . . . . . . .
Blocking Execution of a Console Application That Creates Figures and Terminating Figures by Force . . . . . . . . . . . Passing Arguments to and from a Standalone Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Graphical Applications in Shared Library Targets . . Using the VER Function in a Compiled MATLAB Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-25 5-27 5-28 5-28 Standalone Applications 6 Introduction . . . . . . . .
C Shared Library Target . . . . . . . . . . . . . . . . . . . . . . . . . . . C Shared Library Wrapper . . . . . . . . . . . . . . . . . . . . . . . . . . C Shared Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . Calling a Shared Library . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4 7-4 7-4 7-11 C++ Shared Library Target . . . . . . . . . . . . . . . . . . . . . . . . . C++ Shared Library Wrapper . . . . . . . . . . . . . . . . . . . . . . . . C++ Shared Library Example . .
Reference Information 9 Directories Required for Development and Testing . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Path for Java Development on All Platforms . . . . . . . . . . . Windows Settings for Development and Testing . . . . . . . . . UNIX Settings for Development and Testing . . . . . . . . . . . 9-2 9-2 9-2 9-2 9-3 Directories Required for Run-Time Deployment . . . . . . Path for Java Applications on All Platforms . . . . . . . . . . . .
Functions — Alphabetical List 11 Limitations and Restrictions 12 Limitations About What May Be Compiled . . . . . . . . . . . Compiling MATLAB and Toolboxes . . . . . . . . . . . . . . . . . . . MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Fixing Callback Problems: Missing Functions . . . . . . . . . . Finding Missing Functions in an M-File . . . . . . . . . . . . . . . Suppressing Warnings on UNIX . . . . . . . . . . . . . . . . . . . . .
Compile-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-3 Warning Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-7 depfun Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About depfun Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MCR/Dispatcher Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . XML Parser Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mwArray Class Functions . . . . . . . . . . . . . . . . . . . . . . . . . .
1 Getting Started What Is MATLAB Compiler? (p. 1-2) Brief summary of the product How Does MATLAB Compiler Work? (p. 1-3) High-level description of what the product does Before You Begin (p. 1-5) What you must do before you can use the product Using the GUI to Create and Package a Deployable Component (p. 1-6) Overview of the steps to create a simple application Magic Square Example (p. 1-7) Accessing examples that come with the product and describes one example in detail Using the mcc Command (p.
1 Getting Started What Is MATLAB Compiler? In this section... “Overview of MATLAB Compiler” on page 1-2 “What Is the Deployment Tool? ” on page 1-2 Overview of MATLAB Compiler Use MATLAB® Compiler to convert MATLAB® programs to applications and libraries that you can distribute to end users who do not have MATLAB installed. You can compile M-files, MEX-files, or other MATLAB code. MATLAB Compiler supports all the features of MATLAB, including objects, private functions, and methods.
How Does MATLAB Compiler Work? How Does MATLAB Compiler Work? In this section... “MATLAB Compiler Generated Application or Library” on page 1-3 “Wrapper Files” on page 1-3 “Component Technology File (CTF)” on page 1-4 MATLAB Compiler Generated Application or Library When you package and distribute applications and libraries that are generated by MATLAB Compiler, you must include the MATLAB Component Runtime (MCR) as well as a set of supporting files generated by MATLAB Compiler.
1 Getting Started • For a library, contains the entry points for each public M-file function. Users of libraries generated by MATLAB Compiler must call the library initialization and termination routines in their client code. Component Technology File (CTF) MATLAB Compiler also generates a Component Technology File (CTF), which is independent of the final target type — standalone application or library — but is specific to each operating system platform. This file, which is named with a .
Before You Begin Before You Begin Before you can use MATLAB Compiler, you must have it installed and configured properly on your system. Refer to Chapter 2, “Installation and Configuration” for more information. At a minimum, you must run the following command once after installing a new version of MATLAB Compiler: mbuild -setup If you need information about writing the M-files that you plan to compile, see MATLAB Programming, which is part of the MATLAB product documentation.
1 Getting Started Using the GUI to Create and Package a Deployable Component Open the Deployment Tool by issuing the following command at the MATLAB prompt: deploytool Use the Deployment Tool as follows to create and package either a standalone application or a shared library: 1 Create a new project. 2 Add files that you want to compile. 3 Set properties for building and packaging. 4 Save the project. 5 Build the component. 6 Edit and rebuild as necessary.
Magic Square Example Magic Square Example This example shows you how to: • Access the examples provided with MATLAB Compiler. • Use MATLAB Compiler to create and package a simple standalone application. About the Examples The examples for MATLAB Compiler are in matlabroot\extern\examples\compiler. For matlabroot, substitute the MATLAB root directory on your system. Type matlabroot to see this directory name.
1 Getting Started 4 While in MATLAB, type deploytool to open the Deployment Tool window. The Deployment Tool opens as a dockable window in the MATLAB desktop, and a menu labeled Project is added to the MATLAB menu bar. 5 Create a new project: a. In the Deployment Tool toolbar, click the New Project icon. As an alternative, you can select File > New Deployment Project in the MATLAB menu bar. b.
Magic Square Example at the bottom of the output pane. The Deployment Tool Output pane is dockable; by default it appears across the bottom of the MATLAB desktop. MATLAB Compiler puts the files that are needed for the application in two newly created subdirectories, src and distrib, in the MagicExample directory. A copy of the build log is placed in the src directory. Tip When your source code has been compiled successfully, a file named readme.txt is written to the distrib directory.
1 Getting Started Using the mcc Command Instead of the GUI, you can use the mcc command to run MATLAB Compiler. The following table shows sample commands to create a standalone application or a shared library using mcc at the operating system prompt. Desired Result Standalone application from the M-file Command mcc -m mymfunction.m mymfunction Creates a standalone application named mymfunction.exe on Windows platforms and mymfunction on platforms that are not Windows.
Using the mcc Command Note The -l option is a bundle option that expands into the following: -W lib -T link:lib A bundle is a collection of mcc input options. See matlabroot/toolbox/compiler/bundles for the available bundles. The -W lib option tells MATLAB Compiler to generate a function wrapper for a shared library. The -T link:lib option specifies the target output as a shared library. See Chapter 5, “Compiler Commands”, for more information about using the mcc command and its options.
1 Getting Started Developing and Testing Components on a Development Machine In this section... “Packaging Your Software” on page 1-12 “Replacement of MCRInstaller.
Developing and Testing Components on a Development Machine Platform File Replacing MCRInstaller.zip File Location Windows 32-bit MCRInstaller.exe matlabroot\toolbox\compiler\deploy\win32 Windows 64-bit MCRInstaller.exe matlabroot\toolbox\compiler\deploy\win64 Linux (glnx86) MCRInstaller.bin matlabroot/toolbox/compiler/deploy/glnx86 Linux (glnxa64) MCRInstaller.bin matlabroot/toolbox/compiler/deploy/glnxa64 Mac MATLAB_Component_ Runtime.
1 Getting Started • The CTF archive that MATLAB Compiler creates for your component Configuring the Development Environment by Installing the MCR To test software created by MATLAB Compiler as it will be used by end users without MATLAB, programmers must install the MCR, if it is not already installed on the development machine, and set path environment variables properly. Configuring on Windows Platforms 1 Open the package created by you or the Deployment Tool.
For More Information For More Information About This Look Here Detailed information on standalone applications Chapter 6, “Standalone Applications” Creating libraries Chapter 7, “Libraries” Using the mcc command Chapter 5, “Compiler Commands” Troubleshooting Chapter 8, “Troubleshooting” 1-15
1 1-16 Getting Started
2 Installation and Configuration This chapter describes the system requirements for MATLAB Compiler. It also contains installation and configuration information for all supported platforms. When you install your ANSI C or C++ compiler, you may be required to provide specific configuration details regarding your system. This chapter contains information for each platform that can help you during this phase of the installation process. Requirements (p.
2 Installation and Configuration Requirements In this section... “System Requirements” on page 2-2 “Supported Third-Party Compilers” on page 2-2 System Requirements To install MATLAB Compiler, you must have the proper version of MATLAB installed on your system. The MATLAB Compiler Platform & Requirements page, which is accessible from our Web site, provides this information. MATLAB Compiler imposes no operating system or memory requirements beyond those that are necessary to run MATLAB.
Requirements Supported ANSI C and C++ Windows Compilers Use one of the following 32-bit C/C++ compilers that create 32-bit Windows dynamically linked libraries (DLLs) or Windows applications: • Lcc C version 2.4.1 (included with MATLAB). This is a C-only compiler; it does not work with C++. • Borland C++ versions 5.5, 5.6, and 5.5. (You may see references to these compilers as Borland C++ Builder versions 5.0, 6.0, and Borland C/C++ Free Command-Line Tools, respectively.
2 Installation and Configuration Installation In this section... “Installing MATLAB Compiler” on page 2-4 “Installing an ANSI C or C++ Compiler” on page 2-5 Installing MATLAB Compiler MATLAB Compiler requires a supported ANSI C or C++ compiler installed on your system as well. Refer to the “Installing an ANSI C or C++ Compiler” on page 2-5 for more information. Windows To install MATLAB Compiler on Windows, follow the instructions in the Installation Guide for Windows documentation.
Installation Compiler does not appear as one of the installation choices, contact The MathWorks to get an updated license file (license.dat). Installing an ANSI C or C++ Compiler To install your ANSI C or C++ compiler, follow the vendor’s instructions that accompany your C or C++ compiler. Be sure to test the C or C++ compiler to make sure it is installed and configured properly. Typically, the compiler vendor provides some test procedures.
2 Installation and Configuration Windows (Continued) Issue Comment Running from the command line Make sure you select all relevant options for running your compiler from the command line. Updating the registry If your installer gives you the option of updating the registry, you should do it. Installing Microsoft Visual C/C++ Version 6.0 If you need to change the location where this compiler is installed, you must change the location of the Common directory.
Configuration Configuration In this section... “About the mbuild Utility” on page 2-7 “Configuring an ANSI C or C++ Compiler” on page 2-7 About the mbuild Utility The mbuild script provides an easy way for you to specify an options file that lets you: • Set the default compiler and linker settings for each supported compiler. • Change compilers or compiler settings. • Build your application. mbuild simplifies the process of setting up a C or C++ compiler.
2 Installation and Configuration When you select a compiler to use with MATLAB Compiler, the corresponding options file is activated on your system. To select a default compiler, use mbuild -setup Additional information on the options files is provided in this chapter for those users who may need to modify them to suit their own needs. Many users never have to be concerned with the inner workings of the options files and only need the setup option to initially designate a C or C++ compiler.
Configuration Please verify your choices: Compiler: Microsoft Visual C/C++ 2005 Location: D:\Applications\Microsoft Visual Studio Are these correct?([y]/n): y Trying to update options file: C:\WINNT\Profiles\username\Application Data\MathWorks\MATLAB\current_release\compopts.bat From template: \\sys\MATLAB\BIN\WIN32\mbuildopts\msvc60compp.bat Done ... The preconfigured options files that are included with MATLAB for Windows are shown below. Note These options apply only to the 32-bit version of MATLAB.
2 Installation and Configuration mbuild -setup Using the 'mbuild -setup' command selects an options file that is placed in ~/.matlab/current_release and used by default for 'mbuild'. An options file in the current working directory or specified on the command line overrides the default options file in ~/.matlab/current_release. Options files control which compiler to use, the compiler and link command options, and the run time libraries to link against.
Supported Compiler Restrictions Supported Compiler Restrictions The known restrictions regarding the use of supported compilers on Windows are: • The LCC C compiler does not support C++ or versions of Windows other than 32–bit. • The only compiler that supports the building of COM objects and Excel plug-ins is Microsoft Visual C/C++ (Versions 6.0, 7.1, and 8.0). • The only compiler that supports the building of .NET objects is the Microsoft Visual C# Compiler for the .NET Framework (Versions 1.1 and 2.0).
2 Installation and Configuration Options Files In this section... “Locating the Options File” on page 2-12 “Changing the Options File” on page 2-13 Locating the Options File Windows To locate your options file on Windows, the mbuild script searches the following locations: • Current directory • The user profile directory (see “User Profile Directory Under Windows” on page 2-12 for more information about this directory) mbuild uses the first occurrence of the options file it finds.
Options Files • Current directory • $HOME/.matlab/current_release • matlabroot/bin mbuild uses the first occurrence of the options file it finds. If no options file is found, mbuild displays an error message. Changing the Options File Although it is common to use one options file for all of your MATLAB Compiler related work, you can change your options file at anytime. The setup option resets your default compiler so that the new compiler is used every time.
2 Installation and Configuration default options files (other MATLAB products may place options files in this directory). Do not confuse these user-specific matlab directories with the system matlab directory, where MATLAB is installed. Modifying the Options File. You can use the setup option to change your options file settings on UNIX. For example, if you want to make a change to the current linker settings, or you want to disable a particular set of warnings, you should use the setup option.
3 Compilation Process This chapter provides an overview of how MATLAB Compiler works. In addition, it lists the various sets of input and output files used by MATLAB Compiler. Overview of MATLAB Compiler Technology (p. 3-2) Describes the build process Input and Output Files (p.
3 Compilation Process Overview of MATLAB Compiler Technology In this section... “MATLAB Component Runtime” on page 3-2 “Component Technology File” on page 3-2 “Build Process” on page 3-3 MATLAB Component Runtime MATLAB Compiler 4 uses the MATLAB Component Runtime (MCR), which is a standalone set of shared libraries that enable the execution of M-files. The MCR provides complete support for all features of the MATLAB language.
Overview of MATLAB Compiler Technology Additional Details Multiple CTF archives, such as COM, .NET, or Excel components, can coexist in the same user application, but you cannot mix and match the M-files they contain. You cannot combine encrypted and compressed M-files from multiple CTF archives into another CTF archive and distribute them. All the M-files from a given CTF archive are locked together with a unique cryptographic key.
3 Compilation Process Creating a Standalone Executable Dependency Analysis The first step determines all the functions on which the supplied M-files, MEX-files, and P-files depend. This list includes all the M-files called by the given files as well as files that they call, and so on. Also included are all built-in functions and MATLAB objects.
Overview of MATLAB Compiler Technology Wrapper Code Generation This step generates all the source code needed to create the target component, including • The C/C++ interface code to those M-functions supplied on the command line (foo_main.c). For libraries and components, this file includes all of the generated interface functions. • A component data file that contains information needed to execute the M-code at run-time.
3 Compilation Process Input and Output Files In this section... “Standalone Executable” on page 3-6 “C Shared Library” on page 3-7 “C++ Shared Library” on page 3-9 Standalone Executable In this example, MATLAB Compiler takes the M-files foo.m and bar.m as input and generates a standalone called foo. mcc -m foo.m bar.m 3-6 File Description foo_main.c The main-wrapper C source file containing the program’s main function.
Input and Output Files C Shared Library In this example, MATLAB Compiler takes the M-files foo.m and bar.m as input and generates a C shared library called libfoo. mcc -W lib:libfoo -T link:lib foo.m bar.m File Description libfoo.c The library wrapper C source file containing the exported functions of the library representing the C interface to the two M-functions (foo.m and bar.m) as well as library initialization code. libfoo.h The library wrapper header file.
3 Compilation Process File Description libfoo The shared library binary file. On Windows, this file is libfoo.dll. On Solaris, this file is libfoo.so. Note UNIX extensions vary depending on the platform. See the External Interfaces documentation for additional information. 3-8 libname.exp Exports file used by the linker. The linker uses the export file to build a program that contains exports, usually a dynamic-link library (.dll).
Input and Output Files C++ Shared Library In this example, MATLAB Compiler takes the M-files foo.m and bar.m as input and generates a C++ shared library called libfoo. mcc -W cpplib:libfoo -T link:lib foo.m bar.m File Description libfoo.cpp The library wrapper C++ source file containing the exported functions of the library representing the C++ interface to the two M-functions (foo.m and bar.m) as well as library initialization code. libfoo.h The library wrapper header file.
3 3-10 Compilation Process File Description libname.exp Exports file used by the linker. The linker uses the export file to build a program that contains exports (usually a dynamic-link library (.dll). The import library is used to resolve references to those exports in other programs. libname.lib Import library. An import library is used to validate that a certain identifier is legal, and will be present in the program when the .dll is loaded.
4 Deployment Process This chapter tells you how to deploy compiled M-code to programmers and to end users. Overview (p. 4-2) Describes the deployment process Deploying to Programmers (p. 4-3) Describes the steps used to deploy compiled M-code to programmers Deploying to End Users (p. 4-9) Describes the steps used to deploy compiled M-code to end users Working with the MCR (p.
4 Deployment Process Overview After you create a library, a component, or an application, the next step is typically to deploy it to others to use on their machines, independent of MATLAB. These users could be programmers who want to use the library or component to develop an application, or end users who want to run a standalone application.
Deploying to Programmers Deploying to Programmers In this section... “Steps by the Programmer to Deploy to Programmers” on page 4-3 “What Software Does a Programmer Need?” on page 4-4 Steps by the Programmer to Deploy to Programmers Note If you are programming on the same machine where you created the component, you can skip the steps described here. 1 Create a package that contains the software necessary to support the compiled M-code.
4 Deployment Process What Software Does a Programmer Need? The software that you provide to a programmer who wants to use compiled M-code depends on which of the following kinds of software the programmer will be using: • “Standalone Application” on page 4-4 • “C or C++ Shared Library” on page 4-5 • “.NET Component” on page 4-6 • “COM Component” on page 4-6 • “Java Component” on page 4-7 • “COM Component to Use with Microsoft Excel” on page 4-7 Note MCRInstaller.
Deploying to Programmers Software Module Description MATLAB_Component _Runtime.dmg MATLAB_Component_Runtime.dmg is a (Mac) self-extracting executable that installs the necessary components to develop your application on Mac machines. This file is included with MATLAB Compiler. application_name.ctf Component Technology File archive; platform-dependent file that must correspond to the end user’s platform application_name.
4 Deployment Process Software Module Description libmatrix.ctf Component Technology File archive; platform-dependent file that must correspond to the end user’s platform libmatrix Shared library; extension varies by platform, for example, DLL on Windows libmatrix.h Library header file .NET Component To distribute a .NET component to a development machine, create a package that includes the following files. Software Module Description componentName.ctf Component Technology File componentName.
Deploying to Programmers Software Module Description componentname_ version.dll Component that contains compiled M-code. MCRInstaller.exe Self-extracting MATLAB Component Runtime library utility; platform-dependent file that must correspond to the end user’s platform. MCRInstaller.exe installs MATLAB Component Runtime (MCR), which users of your component need to install on the target machine once per release.
4 Deployment Process Software Module Description MCRInstaller.exe Self-extracting MATLAB Component Runtime library utility; platform-dependent file that must correspond to the end user’s platform. MCRInstaller.exe installs the MATLAB Component Runtime (MCR), which users of your component need to install on the target machine once per release. *.
Deploying to End Users Deploying to End Users In this section...
4 Deployment Process Note The package needed for end users must include the .ctf file, which includes all the files in your preferences directory. Thus, you should make sure that you do not have files in your preferences directory that you do not want to expose to end users. MATLAB preferences set at compile time are inherited by a compiled application.
Deploying to End Users Note for Windows Applications You must have administrative privileges to install the MCR on a target machine since it modifies both the system registry and the system path. Running the MCRInstaller after the MCR has been set up on the target machine requires only user-level privileges. Steps by the End User on UNIX 1 Install the MCR. Locate the MCRInstaller.zip file and copy it to a new directory on your machine.
4 Deployment Process The installation begins. The process takes some time due to the quantity of files that are installed. The MCRInstaller automatically: • Copies the necessary files to the target directory you specified. • Registers the components as needed. • Updates the system path to point to the MCR binary directory, which is //run time/bin/win32. 4 When the installation completes, click Close on the Installation Completed dialog box to exit.
Deploying to End Users Component Description MCRInstaller.exe Self-extracting MATLAB Component Runtime library utility; platform-dependent file that must correspond to the end user’s platform. (Windows) (UNIX) Utility to unzip MCRInstaller.zip (optional). The target machine must have an unzip utility installed. matrixdriver.exe Application unzip (Windows) matrixdriver (UNIX) libmatrix.ctf Component Technology File archive; platform-dependent file that must correspond to the end user’s platform.
4 Deployment Process Software Module Description componentName.dll Component assembly file MCRInstaller.exe MCR Installer (if not already installed on the target machine) application.exe Application COM Application To distribute a COM application that uses components created with MATLAB Builder for .NET or MATLAB Builder for Excel, create a package that includes the following files. Software Module Description componentname.ctf Component Technology File (ctf) archive.
Deploying to End Users Software Module Description componentname.ctf Component Technology File componentname.jar Java package containing Java interface to M-code in componentname.ctf. Microsoft Excel Add-In To distribute an Excel add-in created with MATLAB Builder for Excel, create a package that includes the following files. Software Module Description componentname.
4 Deployment Process application to a Windows machine, you must use the Windows version of MATLAB Compiler to build the application on a Windows machine. Note Since binary formats are different on each platform, the components generated by MATLAB Compiler cannot be moved from platform to platform as is. To deploy an application to a machine with an operating system different from the machine used to develop the application, you must rebuild the application on the desired targeted platform.
Deploying to End Users Note To run extractCTF from any directory, you must add matlabroot/toolbox/compiler/deploy/arch to your PATH environment variable. Run extractCTF.exe from a system prompt. If you run it from MATLAB, be sure to utilize the bang (!) operator. Dependency Analysis Function (depfun) and User Interaction with the Compilation Path MATLAB Compiler uses a dependency analysis function (depfun) to determine the list of necessary files to include in the CTF package.
4 Deployment Process • addpath and rmpath in MATLAB • Passing -I on the mcc command line • Passing -N and -p directories on the mcc command line addpath and rmpath in MATLAB If you run MATLAB Compiler from the MATLAB prompt, you can use the addpath and rmpath commands to modify the MATLAB path before doing a compilation. There are two disadvantages: • The path is modified for the current MATLAB session only.
Deploying to End Users It also retains all subdirectories of the above list that appear on the MATLAB path at compile time. Including -N on the command line allows you to replace directories from the original path, while retaining the relative ordering of the included directories. All subdirectories of the included directories that appear on the original path are also included. In addition, the -N option retains all directories that the user has included on the path that are not under matlabroot/toolbox.
4 Deployment Process Working with the MCR In this section... “Understanding the MCR” on page 4-20 “Installing the MCR and MATLAB on the Same Machine” on page 4-21 “Installing Multiple MCRs on the Same Machine” on page 4-22 Understanding the MCR MATLAB Compiler was designed to work with a large range of applications that use the MATLAB programming language. Because of this, run-time libraries are large.
Working with the MCR Note MCRInstaller.exe has obsoleted the need for the function buildmcr or the creation of MCRInstaller.zip. See “Replacement of MCRInstaller.zip and BUILDMCR Functionality” on page 1-12 for more details. See “Deploying to End Users” on page 4-9 for more information about the general steps for installing the MCR as part of the deployment process. See also “Using MCRInstaller.exe on the Command Line” on page 9-13 for more information.
4 Deployment Process UNIX. To run deployed components on Linux, Linux x86-64, or Solaris, the /run time/ directory must appear on your LD_LIBRARY_PATH before matlabroot/bin/, and XAPPLRESDIR should point to /X11/app-defaults. See “Directories Required for Run-Time Deployment” on page 9-5 for the platform-specific commands.
Working with the MCR Note The feature that allows you to install multiple versions of the MCR on the same machine is currently not supported on Mac OS X. When you receive a new version of MATLAB, you must recompile and redeploy all of your applications and components. Also, when you install a new MCR onto a target machine, you must delete the old version of the MCR and install the new one. You can only have one version of the MCR on the target machine.
4 Deployment Process Deploying a Standalone Application on a Network Drive You can deploy a compiled standalone application to a network drive so that it can be accessed by all network users without having them install the MCR on their individual machines. 1 On any Windows machine, execute MCRInstaller.exe to install the MATLAB Component Runtime (MCR). 2 Copy the entire MCR directory (the directory where MCR is installed) onto a network drive.
MATLAB Compiler Deployment Messages MATLAB Compiler Deployment Messages To enable display of MATLAB Compiler deployment messages, see “Show MATLAB Compiler Deployment messages” in MATLAB Desktop Tools and Development Environment.
4 Deployment Process Using MATLAB Compiler Generated DLLs in Windows Services If you have a Windows service that is built using DLL files generated by MATLAB Compiler, do the following to ensure stable performance: 1 Create a file named java.opts. 2 Add the following line to the file: -Xrs 3 Save the file to: MCRROOT/version/bin/win32, where MCRROOT is the installation directory of the MATLAB Component Runtime and version is the MCR version (for example, v74 for MATLAB Compiler 4.4 (R2006a)).
5 Compiler Commands This chapter describes mcc, which is the command that invokes MATLAB Compiler. Command Overview (p. 5-2) Details on using the mcc command Using Macros to Simplify Compilation (p. 5-5) Information on macros and how they can simplify your work Using Pathnames (p. 5-7) Specifying pathnames Using Bundle Files (p. 5-8) How to use bundle files to replace sequences of commands Using Wrapper Files (p. 5-10) Details on wrapper files Interfacing M-Code to C/C++ Code (p.
5 Compiler Commands Command Overview In this section... “Compiler Options” on page 5-2 “Combining Options” on page 5-2 “Conflicting Options on the Command Line” on page 5-3 “Using File Extensions” on page 5-3 Compiler Options mcc is the MATLAB command that invokes MATLAB Compiler. You can issue the mcc command either from the MATLAB command prompt (MATLAB mode) or the DOS or UNIX command line (standalone mode). You may specify one or more MATLAB Compiler option flags to mcc.
Command Overview mcc -vW main -T link:exe myfun % Options combined This format is not valid: mcc -Wv main -T link:exe myfun In cases where you have more than one option that takes arguments, you can only include one of those options in a combined list and that option must be last. You can place multiple combined lists on the mcc command line. If you include any C or C++ filenames on the mcc command line, the files are passed directly to mbuild, along with any MATLAB Compiler generated C or C++ files.
5 Compiler Commands extension, when compiling with mcc or you may encounter unpredictable results. Note P-files (.p) have precedence over M-files, therefore if both P-files and M-files reside in a directory, and a filename is specified without an extension, the P-file will be selected.
Using Macros to Simplify Compilation Using Macros to Simplify Compilation In this section... “Macro Options” on page 5-5 “Understanding a Macro Option” on page 5-5 Macro Options MATLAB Compiler, through its exhaustive set of options, gives you access to the tools you need to do your job. If you want a simplified approach to compilation, you can use one simple option, i.e., macro, that allows you to quickly accomplish basic compilation tasks.
5 Compiler Commands -m Macro Option Function -W main Produce a wrapper file suitable for a standalone application. -T link:exe Create an executable link as the output. Changing Macro Options You can change the meaning of a macro option by editing the corresponding macro_option bundle file in matlabroot/toolbox/compiler/bundles. For example, to change the -m macro, edit the file macro_option_m in the bundles directory. Note This changes the meaning of -m for all users of this MATLAB installation.
Using Pathnames Using Pathnames If you specify a full pathname to an M-file on the mcc command line, MATLAB Compiler 1 Breaks the full name into the corresponding pathname and filenames ( and ). 2 Replaces the full pathname in the argument list with “-I ”. For example, mcc -m /home/user/myfile.m would be treated as mcc -m -I /home/user myfile.m In rare situations, this behavior can lead to a potential source of confusion.
5 Compiler Commands Using Bundle Files Bundle files provide a convenient way to group sets of MATLAB Compiler options and recall them as needed. The syntax of the bundle file option is -B [:,,...,] When used on the mcc command line, the bundle option -B replaces the entire string with the contents of the specified file. The file should contain only mcc command line options and corresponding arguments and/or other filenames. The file may contain other -B options.
Using Bundle Files Note You can use the -B option with a replacement expression as is at the DOS or UNIX prompt. To use -B with a replacement expression at the MATLAB prompt, you must enclose the expression that follows the -B in single quotes when there is more than one parameter passed. For example, >>mcc -B csharedlib:libtimefun weekday data tic calendar toc can be used as is at the MATLAB prompt because libtimefun is the only parameter being passed.
5 Compiler Commands Using Wrapper Files In this section... “What Are Wrapper Files?” on page 5-10 “Main File Wrapper” on page 5-10 “C Library Wrapper” on page 5-11 “C++ Library Wrapper” on page 5-12 What Are Wrapper Files? Wrapper files encapsulate, or wrap, the M-files in your application with an interface that enables the M-files to operate in a given target environment.
Using Wrapper Files y = 0; You can compile sample.m into a POSIX main application. If you call sample from MATLAB, you get sample hello world ans = hello ans = world ans = 0 If you compile sample.m and call it from the DOS shell, you get C:\> sample hello world ans = hello ans = world C:\> The difference between the MATLAB and DOS/UNIX environments is the handling of the return value.
5 Compiler Commands of the compiled M-functions. The export list contains the set of symbols that are exported from a C shared library. Note You must generate a library wrapper file when calling any MATLAB Compiler generated code from a larger application. C++ Library Wrapper The -W cpplib:libname option produces the C++ library wrapper file. This option allows the inclusion of an arbitrary set of M-files into a library.
Interfacing M-Code to C/C++ Code Interfacing M-Code to C/C++ Code In this section... “Overview” on page 5-13 “C Example” on page 5-13 Overview MATLAB Compiler supports calling arbitrary C/C++ functions from your M-code. You simply provide an M-function stub that determines how the code will behave in M, and then provide an implementation of the body of the function in C or C++. C Example Suppose you have a C function that reads data from a measurement device.
5 Compiler Commands t = t + 0.05; y = sin(t); The next step is to replace the implementation of the collect_one function with a C implementation that provides the correct value from the device each time it is requested. This is accomplished by using the %#external pragma. The %#external pragma informs MATLAB Compiler that the function will be hand written and will not be generated from the M-code. This pragma affects only the single function in which it appears.
Interfacing M-Code to C/C++ Code %#external persistent t; if (isempty(t)) t = 0; end t = t + 0.05; y = sin(t); When this file is compiled, MATLAB Compiler creates the additional header file collect_one_external.h, which contains the interface between MATLAB Compilergenerated code and your code. In this example, it would contain: extern bool collect_one(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]); Note The return type has changed from void to bool in MATLAB Compiler post-R13.
5 Compiler Commands static double t = 0.0; t = t + 0.05; return sin(t); } To generate the application, use mcc -m collect.m measure.c Note For information on the mxArray, see the External Interfaces documentation.
Using Pragmas Using Pragmas In this section... “Using feval” on page 5-17 “Example: Using %#function” on page 5-17 Using feval In standalone C and C++ modes, the pragma %#function informs MATLAB Compiler that the specified function(s) should be included in the compilation, whether or not the MATLAB Compiler dependency analysis detects it. Without this pragma, the MATLAB Compiler dependency analysis will not be able to locate and compile all M-files used in your application.
5 Compiler Commands %#function bartlett, barthannwin, blackman, blackmanharris, bohmanwin, chebwin, flattopwin, gausswin, hamming, hann, kaiser, nuttallwin, parzenwin, rectwin, tukeywin, triang window = feval(filterName,N); % Apply the window to the data. ret = data.
Script Files Script Files In this section... “Converting Script M-Files to Function M-Files” on page 5-19 “Including Script Files in Deployed Applications” on page 5-20 Converting Script M-Files to Function M-Files MATLAB provides two ways to package sequences of MATLAB commands: • Function M-files • Script M-files These two categories of M-files differ in three important respects: • You can pass arguments to function M-files, but not to script M-files.
5 Compiler Commands Running this script M-file from a MATLAB session creates variables m and t in your MATLAB workspace browser. MATLAB Compiler cannot compile houdini.m because it is a script. Convert this script M-file into a function M-file by simply adding a function header line. function houdini(sz) m = magic(sz); % Assign magic square to m. t = m .^ 3; % Cube each element of m. disp(t) % Display the value of t. MATLAB Compiler can now compile houdini.m.
Script Files function houdini_fcn houdini; To produce the houdini_fcn , which will call the houdini.
5 Compiler Commands Compiler Tips In this section... “Calling Built-In Functions from C or C++” on page 5-22 “Calling a Function from the Command Line” on page 5-23 “Using MAT-Files in Deployed Applications” on page 5-23 “Recommended Location of .CTF Files” on page 5-23 “Compiling a GUI That Contains an ActiveX Control” on page 5-24 “Debugging MATLAB Compiler Generated Executables” on page 5-24 “Deploying Applications That Call the Java Native Libraries” on page 5-25 “Locating .
Compiler Tips m = magic(n); Calling a Function from the Command Line You can make a MATLAB function into a standalone that is directly callable from the system command line. All the arguments passed to the MATLAB function from the system command line are strings. Two techniques to work with these functions are: • Modify the original MATLAB function to test each argument and convert the strings to numbers. • Write a wrapper MATLAB function that does this test and then calls the original MATLAB function.
5 Compiler Commands ..\myProgram.exe you may see the error: Cannot find the directory containing the 'myProgram' component, which is required by this application. Make sure the directory containing 'myProgram.ctf' is on your dynamic load library path (PATH on Windows, or LD_LIBRARY_PATH on Linux, for example), or your application search path (PATH on both Windows and Linux). Error initializing CTF Archive.
Compiler Tips Deploying Applications That Call the Java Native Libraries If your application interacts with Java, you need to specify the search path for native method libraries by editing librarypath.txt and deploying it. 1 Copy librarypath.txt from matlabroot/toolbox/local/librarypath.txt. 2 Place librarypath.txt in //toolbox/local. refers to the complete path where the MCR library archive files are installed on your machine. 3 Edit librarypath.
5 Compiler Commands • There are one or more figures you want to remain open. • The function that displays the graphics requires user input before continuing. • The function that calls the figures was called from main() in a console program. When mclWaitForFiguresToDie is called, execution of the calling program is blocked if any figures created by the calling object remain open. mclWaitForFiguresToDie is utilized by both .NET Builder and Java Builder through the use of wrapper methods.
Compiler Tips Passing Arguments to and from a Standalone Application To pass input arguments to a MATLAB Compiler generated standalone application, you pass them just as you would to any console-based application. For example, to pass a file called helpfile to the compiled function called filename, use filename helpfile To pass numbers or letters (e.g., 1, 2, and 3), use filename 1 2 3 Do not separate the arguments with commas.
5 Compiler Commands • You cannot return back values from your standalone application to the user. The only way to return values from compiled code is to either display it on the screen or store it in a file. To display your data on the screen, you either need to unsuppress (do not use semicolons) the commands whose results yield data you want to return to the screen or, use the disp command to display the value.
6 Standalone Applications This chapter describes how to use MATLAB Compiler to code and build standalone applications. You can distribute standalone applications to users who do not have MATLAB on their systems. Introduction (p. 6-2) Overview of using MATLAB Compiler to build standalone applications C Standalone Application Target (p. 6-3) Examples of using MATLAB Compiler to generate and deploy standalone C applications Coding with M-Files Only (p.
6 Standalone Applications Introduction Suppose you want to create an application that calculates the rank of a large magic square. One way to create this application is to code the whole application in C or C++; however, this would require writing your own magic square, rank, and singular value routines. An easier way to create this application is to write it as one or more M-files, taking advantage of the power of MATLAB and its tools.
C Standalone Application Target C Standalone Application Target In this section... “Compiling the Application” on page 6-3 “Testing the Application” on page 6-3 “Deploying the Application” on page 6-6 “Running the Application” on page 6-7 Compiling the Application This example takes an M-file, magicsquare.m, and creates a standalone C application, magicsquare. 1 Copy the file magicsquare.m from matlabroot/extern/examples/compiler to your work directory. 2 To compile the M-code, use mcc -mv magicsquare.
6 Standalone Applications Note Testing your application on your development machine is an important step to help ensure that your application is compilable. To verify that your application compiled properly, you must test all functionality that is available with the application. If you receive an error message similar to Undefined function or Attempt to execute script script_name as a function, it is likely that the application will not run properly on deployment machines.
C Standalone Application Target matlabroot/sys/java/jre/sol64/jre1.6.0/lib/sparcv9/native_threads: matlabroot/sys/java/jre/sol64/jre1.6.0/lib/sparcv9/server: matlabroot/sys/java/jre/sol64/jre1.6.0/lib/sparcv9: setenv XAPPLRESDIR matlabroot/X11/app-defaults Linux x86-64 setenv LD_LIBRARY_PATH matlabroot/sys/os/glnxa64: matlabroot/bin/glnxa64: matlabroot/extern/lib/glnxa64: matlabroot/sys/java/jre/glnxa64/jre1.6.0/lib/amd64/native_threads: matlabroot/sys/java/jre/glnxa64/jre1.6.
6 Standalone Applications The results are displayed as ans = 16 5 9 4 2 11 7 14 3 10 6 15 13 8 12 1 Deploying the Application You can distribute a MATLAB Compiler generated standalone to any target machine that has the same operating system as the machine on which the application was compiled. For example, if you want to deploy an application to a Windows machine, you must use MATLAB Compiler to build the application on a Windows machine.
C Standalone Application Target UNIX Distribute and package your standalone application on UNIX by packaging the following files and distributing them to the deployment machine. Component Description MCRInstaller.bin MATLAB Component Runtime library archive; platform-dependent file that must correspond to the end user’s platform unzip Utility to unzip MCRInstaller.zip (optional). The target machine must have an unzip utility installed. magicsquare.
6 Standalone Applications Note On Windows XP, this directory is automatically added to your path. Preparing UNIX Machines 1 Install the MCR by unzipping MCRInstaller.zip in a directory, for example, /home//MCR. You may choose any directory except matlabroot or any directory below matlabroot. Note This documentation uses to refer to the directory where these MCR library archive files are installed on your machine.
C Standalone Application Target setenv LD_LIBRARY_PATH /usr/lib/lwp: //run time/sol64: //sys/os/sol64: //sys/java/jre/sol64/jre1.6.0/lib/sparcv9/native_threads: //sys/java/jre/sol64/jre1.6.0/lib/sparcv9/server: //sys/java/jre/sol64/jre1.6.
6 Standalone Applications Caution There is a limitation regarding directories on your path. If the target machine has a MATLAB installation, the directories must be first on the path to run the deployed application. To run MATLAB, the matlabroot directories must be first on the path. This restriction only applies to configurations involving an installed MCR and an installed MATLAB on the same machine.
Coding with M-Files Only Coding with M-Files Only In this section... “M-File Advantages” on page 6-11 “Example” on page 6-11 M-File Advantages One way to create a standalone application is to write all the source code in one or more M-files or MEX-files as in the previous magic square example. Coding an application with M allows you to take advantage of the MATLAB interactive development environment.
6 Standalone Applications function main r = mrank(5) Compiling the Example To compile these functions into code that can be built into a standalone application, invoke MATLAB Compiler. mcc -m main mrank The -m option causes MATLAB Compiler to generate C source code suitable for standalone applications. For example, MATLAB Compiler generates C source code files main_main.c and main_mcc_component_data.c. main_main.c contains a C function named main; main_mcc_component_data.
Mixing M-Files and C or C++ Mixing M-Files and C or C++ In this section... “Examples Overview” on page 6-13 “Simple Example” on page 6-13 “Advanced C Example” on page 6-18 Examples Overview The examples in this section illustrate how to mix M-files and C or C++ source code files: • The first example is a simple application that mixes M-files and C code. • The second example illustrates how to write C code that calls a compiled M-file.
6 Standalone Applications mrank.m mrank.m contains a function that returns a vector of the ranks of the magic squares from 1 to n. function r = mrank(n) r = zeros(n,1); for k = 1:n r(k) = rank(magic(k)); end Copy mrank.m, printmatrix.m, mrankp.c, main_for_lib.c, and main_for_lib.h into your current directory. Build Process The steps needed to build this standalone application are 1 Compile the M-code. 2 Generate the library wrapper file. 3 Create the binary .
Mixing M-Files and C or C++ MATLAB Compiler generates the following C source code files: • libPkg.c • libPkg.h • libPkg_mcc_component_data.
6 Standalone Applications This command invokes mbuild to compile the resulting MATLAB Compiler generated source files with the existing C source files (mrankp.c and main_for_lib.c) and link against the required libraries. MATLAB Compiler provides two different versions of mrankp.c in the matlabroot/extern/examples/compiler directory: • mrankp.c contains a POSIX-compliant main function. mrankp.c sends its output to the standard output stream and gathers its input from the standard input stream.
Mixing M-Files and C or C++ } mclInitializeApplication(NULL,0); libPkgInitialize();/* Initialize library of M-Functions */ /* Create a 1-by-1 matrix containing n. */ N = mxCreateDoubleScalar(n); /* Call mlfMrank, the compiled version of mrank.m. */ mlfMrank(1, &R, N); /* Print the results. */ mlfPrintmatrix(R); /* Free the matrices allocated during this computation.
6 Standalone Applications To create and manipulate mxArray * variables in your C code, you can call the mx routines described in the External Interfaces documentation. For example, to create a 1-by-1 mxArray * variable named N with real data, mrankp calls mxCreateDoubleScalar. N = mxCreateDoubleScalar(n); mrankp can now call mlfMrank, passing the initialized N as the sole input argument. R = mlfMrank(1,&R,N); mlfMrank returns its output in a newly allocated mxArray * variable named R.
Mixing M-Files and C or C++ • main_for_lib.c, which contains one main function • main_for_lib.h, which is the header for structures used in main_for_lib.c and multargp.c multarg.m specifies two input parameters and returns two output parameters. function [a,b] = multarg(x,y) a = (x + y) * pi; b = svd(svd(a)); The code in multargp.c calls mlfMultarg and then displays the two values that mlfMultarg returns. #include #include #include #include "libMultpkg.
6 Standalone Applications /* Initialize with a print handler to tell mlfPrintMatrix * how to display its output.
Mixing M-Files and C or C++ The program first displays the contents of a 3-by-3 matrix a, and then displays the contents of scalar b. 6.2832 +34.5575i 12.5664 +34.5575i 18.8496 +18.8496i 25.1327 +25.1327i 31.4159 +31.4159i 37.6991 +37.6991i 43.9823 +43.9823i 50.2655 +28.2743i 56.5487 +28.2743i 143.4164 Explanation of This C Code Invoking MATLAB Compiler on multarg.m generates the C function prototype.
6 6-22 Standalone Applications
7 Libraries This chapter describes how to use MATLAB Compiler to create libraries. Introduction (p. 7-2) Overview of shared libraries Addressing mwArrays Above the 2 GB Limit (p. 7-3) How to enable extended addressing for mwArrays larger than 2 GB C Shared Library Target (p. 7-4) Creating and distributing C shared libraries C++ Shared Library Target (p. 7-17) Creating and distributing C++ shared libraries MATLAB Compiler Generated Interface Functions (p.
7 Libraries Introduction You can use MATLAB Compiler to create C or C++ shared libraries (DLLs on Windows) from your MATLAB algorithms. You can then write C or C++ programs that can call the MATLAB functions in the shared library, much like calling the functions from the MATLAB command line.
Addressing mwArrays Above the 2 GB Limit Addressing mwArrays Above the 2 GB Limit As of R2007b, you can now address mwArrays above the 2 GB limit on 64-bit machines. Enable this by defining MX_COMPAT_32_OFF in your mbuild step. Defining MX_COMPAT_32_OFF causes both mwSize and mwIndex to be defined to size_t (an unsigned type on both 32-bit and 64-bit machines). Not defining MS_COMPAT_32_OFF (the default behavior) causes both mwSize and mwIndex to be defined as signed ints.
7 Libraries C Shared Library Target In this section... “C Shared Library Wrapper” on page 7-4 “C Shared Library Example” on page 7-4 “Calling a Shared Library” on page 7-11 C Shared Library Wrapper The C library wrapper option allows you to create a shared library from an arbitrary set of M-files on both Windows and UNIX. MATLAB Compiler generates a wrapper file, a header file, and an export list. The header file contains all of the entry points for all of the compiled M-functions.
C Shared Library Target matlabroot/extern/examples/compiler/multiplymatrix.m matlabroot/extern/examples/compiler/eigmatrix.m matlabroot/extern/examples/compiler/matrixdriver.c Note matrixdriver.c contains the standalone application’s main function. 2 To create the shared library, enter the following command on a single line: mcc -B csharedlib:libmatrix addmatrix.m multiplymatrix.m eigmatrix.
7 Libraries Note If your driver application displays MATLAB figure windows, you should include a call to mclWaitForFiguresToDie(NULL) before calling the Terminate functions and mclTerminateApplication in the following two steps. 5 Call, once for each library, Terminate, to destroy the associated MCR. 6 Call mclTerminateApplication to free resources associated with the global MCR state. 7 Clean up variables, close files, etc., and exit. This example uses matrixdriver.
C Shared Library Target Note This command assumes that the shared library and the corresponding header file created from step 2 are in the current working directory. On UNIX, if this is not the case, replace the “.” (dot) following the -L and -I options with the name of the directory that contains these files, respectively. On Windows, if this is not the case, specify the full path to libmatrix.lib, and use a -I option to specify the directory containing the header file.
7 Libraries Note Testing your application on your development machine is an important step to help ensure that your application is compilable. To verify that your application compiled properly, you must test all functionality that is available with the application. If you receive an error message similar to Undefined function or Attempt to execute script script_name as a function, it is likely that the application will not run properly on deployment machines.
C Shared Library Target Creating Shared Libraries from C with mbuild mbuild can also create shared libraries from C source code. If a file with the extension .exports is passed to mbuild, a shared library is built. The .exports file must be a text file, with each line containing either an exported symbol name, or starting with a # or * in the first column (in which case it is treated as a comment line). If multiple .exports files are specified, all symbol names in all specified .exports files are exported.
7 Libraries Component Description libmatrix.ctf Component Technology File archive; platform-dependent file that must correspond to the end user’s platform. libmatrix Shared library; extension varies by platform. Extensions are: • Windows — .dll • Solaris, Linux, Linux x86-64 — .so • Mac OS X — .dylib Note You can distribute a MATLAB Compiler generated standalone application to any target machine that has the same operating system as the machine on which the application was compiled.
C Shared Library Target Component Description libmatrix.ctf Component Technology File archive; platform-dependent file that must correspond to the end user’s platform libmatrix Shared library; extension varies by platform, for example, DLL on Windows libmatrix.h Library header file Calling a Shared Library At run-time, there is an MCR instance associated with each individual shared library.
7 Libraries Caution You must call mclInitializeApplication once at the beginning of your driver application. You must make this call before calling any other MathWorks functions. This also applies to shared libraries. Avoid calling mclInitializeApplication multiple times in an application as it will cause the application to hang. After you call mclTerminateApplication, you may not call mclInitializeApplication again. No MathWorks functions may be called after mclTerminateApplication.
C Shared Library Target if (!libmatrixInitialize()){ fprintf(stderr,"could not initialize the library properly\n"); return -1; } /* Create the input data */ in1 = mxCreateDoubleMatrix(3,3,mxREAL); in2 = mxCreateDoubleMatrix(3,3,mxREAL); memcpy(mxGetPr(in1), data, 9*sizeof(double)); memcpy(mxGetPr(in2), data, 9*sizeof(double)); /* Call the library function */ mlfAddmatrix(1, &out, in1, in2); /* Display the return value of the library function */ printf("The value of added matrix is:\n"); display(out); /* De
7 Libraries Caution mclInitializeApplication can only be called once per application. Calling it a second time generates an error, and will cause the function to return false. This function must be called before calling any C-Mex function or MAT-file API function. Using a Shared Library To use a MATLAB Compiler generated shared library in your application, you must perform the following steps: 1 Include the generated header file for each library in your application.
C Shared Library Target Note On Windows, if you want to have your shared library call a MATLAB shared library (as generated by MATLAB Compiler), the MATLAB library initialization function (e.g., Initialize, Terminate, mclInitialize, mclTerminate) cannot be called from your shared library during the DllMain(DLL_ATTACH_PROCESS) call. This applies whether the intermediate shared library is implicitly or explicitly loaded. You must place the call somewhere after DllMain().
7 Libraries where mylibrarymfile is the name of an M-file you would like to use when loading this library. This step only needs to be performed once to generate an M-file for the library. In the code that is be compiled, you can now call loadlibrary with the following syntax: loadlibrary(library, @mylibrarymfile, 'alias', alias) With MATLAB Compiler versions 4.0.1 (R14+) and later, generated M-files will automatically be included in the CTF file as part of the compilation process.
C++ Shared Library Target C++ Shared Library Target In this section... “C++ Shared Library Wrapper” on page 7-17 “C++ Shared Library Example” on page 7-17 C++ Shared Library Wrapper The C++ library wrapper option allows you to create a shared library from an arbitrary set of M-files. MATLAB Compiler generates a wrapper file and a header file. The header file contains all of the entry points for all of the compiled M-functions.
7 Libraries Writing the Driver Application Note Due to name mangling in C++, you must compile your driver application with the same version of your third-party compiler that you use to compile your C++ shared library. This example uses a C++ version of the matrixdriver application, matrixdriver.cpp. In the C++ version, arrays are represented by objects of the class mwArray. Every mwArray class object contains a pointer to a MATLAB array structure.
C++ Shared Library Target void *run_main(void *x) { int *err = (int *)x; if (err == NULL) return 0; // // // if { Call application and library initialization. Perform this initialization before calling any API functions or Compiler-generated libraries.
7 Libraries std::cout << "Value of added matrix is:" << std::endl; std::cout << out << std::endl; multiplymatrix(1, out, in1, in2); std::cout << "The value of the multiplied matrix is:" << std::endl; std::cout << out << std::endl; eigmatrix(1, std::cout << << std::cout << out, in1); "The eigenvalues of the first matrix are:" std::endl; out << std::endl; } catch (const mwException& e) { std::cerr << e.what() << std::endl; *err = -2; } catch (...
C++ Shared Library Target Compiling the Driver Application To compile the matrixdriver.cpp driver code, you use your C++ compiler. By executing the following mbuild command that corresponds to your development platform, you will use your C++ compiler to compile the code. mbuild matrixdriver.cpp libmatrixp.lib mbuild matrixdriver.cpp -L. -lmatrixp -I. (Windows) (UNIX) Note This command assumes that the shared library and the corresponding header file are in the current working directory.
7 Libraries M-Functions with No Return Values. void (); M-Functions with at Least One Return Value. void (int number_of_return_values, , ); In this case, represents a comma-separated list of type const mwArray& and represents a comma-separated list of type mwArray&.
MATLAB Compiler Generated Interface Functions MATLAB Compiler Generated Interface Functions In this section...
7 Libraries For a C++ Application on Windows mcc -W cpplib:libtrianglep -T link:lib sierpinski.m mbuild triangle.cpp main_for_lib.c libtrianglep.lib For a C++ Application on UNIX mcc -W cpplib:libtriangle -T link:lib sierpinski.m mbuild triangle.cpp main_for_lib.c -L. -ltriangle -I. These commands create a main program named triangle, and a shared library named libtriangle. The library exports a single function that uses a simple iterative algorithm (contained in sierpinski.
MATLAB Compiler Generated Interface Functions In this example, MATLAB Compiler places all of the generated functions into the generated file libtriangle.c or libtriangle.cpp. Structure of Programs That Call Shared Libraries All programs that call MATLAB Compiler generated shared libraries have roughly the same structure: 1 Declare variables and process/validate input arguments. 2 Call mclInitializeApplication, and test for success.
7 Libraries most likely this is the version your application will call. In this example, this form of the initialization function is called libtriangleInitialize. bool libtriangleInitialize(void) This function creates an MCR instance using the default print and error handlers, and other information generated during the compilation process. However, if you want more control over how printed output and error messages are handled, you may call the second form of the function, which takes two arguments.
MATLAB Compiler Generated Interface Functions you modify the generated DllMain (which we do not recommend you do), make sure you preserve this part of its functionality. Library termination is simple. void libtriangleTerminate(void) Call this function (once for each library) before calling mclTerminateApplication. Print and Error Handling Functions By default, MATLAB Compiler generated applications and shared libraries send printed output to standard output and error messages to standard error.
7 Libraries However, the default implementation of the print handler is slightly different. It sends the output to the standard error output stream, but if the string does not end with carriage return, the error handler adds one. If you replace the default error handler with one of your own, you should perform this check as well, or some of the error messages printed by the MCR will not be properly formatted.
MATLAB Compiler Generated Interface Functions Note For C shared libraries, MATLAB Compiler generates the mlx and mlf functions as described in this section. For C++ shared libraries, MATLAB Compiler generates the mlx function the same way it does for the C shared library. However, MATLAB Compiler generates a modified mlf function with these differences: • The mlf before the function name is dropped to keep compatibility with R13. • The arguments to the function are mwArray instead of mxArray.
7 Libraries Note that in both cases, the generated functions allocate memory for their return values. If you do not delete this memory (via mxDestroyArray) when you are done with the output variables, your program will leak memory. Your program may call whichever of these functions is more convenient, as they both invoke your M-file function in an identical fashion. Most programs will likely call the mlf form of the function to avoid managing the extra arrays required by the mlx form.
MATLAB Compiler Generated Interface Functions For example, consider this M-file interface: [a,b,varargout] = myfun(x,y,z,varargin) The corresponding C interface for this is void mlfMyfun(int numOfRetVars, mxArray **a, mxArray **b, mxArray **varargout, mxArray *x, mxArray *y, mxArray *z, mxArray *varargin) In this example, the number of elements in varargout is (numOfRetVars 2), where 2 represents the two actual variables, a and b, being returned.
7 Libraries Using C/C++ Shared Libraries on Mac OS X To use a MATLAB Compiler generated library on Mac OS X, you must create a separate thread that initializes the shared library and call that library’s functions. The main thread of your application must create and execute a CFRunLoop. The main thread of the application is the thread that calls your driver program’s main() function.
Using C/C++ Shared Libraries on Mac OS X * *=============================================================*/ #include #ifdef __APPLE_CC__ #include #endif /* Include the MCR header file and the library specific header * file as generated by MATLAB Compiler */ #include "libmatrix.
7 Libraries memcpy(mxGetPr(in1), data, 9*sizeof(double)); memcpy(mxGetPr(in2), data, 9*sizeof(double)); /* Call the library intialization routine and make sure that * the library was initialized properly. */ if (!libmatrixInitialize()){ fprintf(stderr,"Could not initialize the library.
Using C/C++ Shared Libraries on Mac OS X * mclTerminateApplication terminates the entire * application and exits with the exit code set using * mclSetExitCode. Note that this behavior is only on MAC * platform. */ #ifdef __APPLE_CC__ mclSetExitCode(*err); #endif mclTerminateApplication(); return 0; } /*DISPLAY This function will display the double matrix stored * in an mxArray. This function assumes that the mxArray passed * as input contains double array.
7 Libraries int main() { int err = 0; #ifdef __APPLE_CC__ pthread_t id; pthread_create(&id, NULL, run_main, &err); CFRunLoopSourceContext sourceContext; sourceContext.version = 0; sourceContext.info = NULL; sourceContext.retain = NULL; sourceContext.release = NULL; sourceContext.copyDescription = NULL; sourceContext.equal = NULL; sourceContext.hash = NULL; sourceContext.schedule = NULL; sourceContext.cancel = NULL; sourceContext.
Using C/C++ Shared Libraries on Mac OS X • You need to call mclSetExitCode with the appropriate exit status. Also, note that you should call mclTerminateapplication in the end of your application. mclTerminateApplication terminates the entire application and exits with the exit code set using mclSetExitCode. • In this example, the main() function creates a new thread using pthread_create, and passes the address of the run_main() function to it.
7 Libraries About Memory Management and Cleanup In this section... “Overview” on page 7-38 “Passing mxArrays to Shared Libraries” on page 7-38 Overview Generated C++ code provides consistent garbage collection via the object destructors and the MCR’s internal memory manager optimizes to avoid heap fragmentation. If memory constraints are still present on your system, try preallocating arrays in M. This will reduce the number of calls to the memory manager, and the degree to which the heap fragments.
8 Troubleshooting mbuild (p. 8-2) Issues involving the mbuild utility and creating standalone applications MATLAB Compiler (p. 8-4) Issues involving MATLAB Compiler Deployed Applications (p.
8 Troubleshooting mbuild This section identifies some of the more common problems that might occur when configuring mbuild to create standalone applications. Options File Not Writeable. When you run mbuild -setup, mbuild makes a copy of the appropriate options file and writes some information to it. If the options file is not writeable, you are asked if you want to overwrite the existing options file.
mbuild before starting MATLAB. If this works correctly, then you should check your .cshrc file for problems setting the PATH environment variable. Cannot Locate Your Compiler (Windows). If mbuild has difficulty locating your installed compilers, it is useful to know how it finds compilers. mbuild automatically detects your installed compilers by first searching for locations specified in the following environment variables: • BORLAND for Borland C/C++, Versions 5.5 and 5.
8 Troubleshooting MATLAB Compiler Typically, problems that occur when building standalone C and C++ applications involve mbuild. However, it is possible that you may run into some difficulty with MATLAB Compiler. A good source for additional troubleshooting information for MATLAB Compiler is the MATLAB Compiler Product Support page at the MathWorks Web site. Borland Compiler Does Not Work with the Builder Products.
MATLAB Compiler when you run your standalone that was generated by MATLAB Compiler, you should check the following: • Do you have a startup.m file that calls addpath? If so, this will cause run-time errors. As a workaround, use isdeployed to have the addpath command execute only from MATLAB. For example, use a construct such as: if ~isdeployed addpath(path); end • Verify that the .ctf archive file self extracted and that you have write permission to the directory.
8 Troubleshooting To verify that the MCR is properly located on your path, from a development Windows machine, confirm that matlabroot\bin\win32, where matlabroot is your root MATLAB directory, appears on your system path ahead of any other MATLAB installations. From a Windows target machine, verify that \\run time\win32, where is your root MCR directory, appears on your system path.
MATLAB Compiler at the beginning of your code and after the include statements, the warning will not recur.
8 Troubleshooting Deployed Applications Failed to decrypt file. The M-file "\toolbox\compiler\deploy\matlabrc.m" cannot be executed. The application is trying to use a CTF archive that does not belong to it. Applications and CTF archives are tied together at compilation time by a unique cryptographic key, which is recorded in both the application and the CTF archive. The keys must match at run time. If they don’t match, you will get this error.
Deployed Applications ??? Error: File: /home/username/ Line: 1651 Column: 8 Arguments to IMPORT must either end with ".*" or else specify a fully qualified class name: "" fails this test. The import statement is referencing a Java class () that MATLAB Compiler (if the error occurs at compile time) or the MCR (if the error occurs at run time) cannot find.
8 Troubleshooting • Ensure that your application runs in MATLAB (uncompiled) without this error. • Ensure that MATLAB starts up without this error. • Verify that the generated CTF archive contains a file called matlabrc.m. • Verify that the generated code (in the *_mcc_component_data.c* file) adds the CTF archive directory containing matlabrc.m to the MCR path. • Delete the *_mcr directory and rerun the application. • Recompile the application.
Deployed Applications Linker cannot find library and fails to create standalone application (win32 and win64). If you try building your standalone application without mbuild, you must link to the following dynamic library: mclmcrrt.lib This library is found in one of the following locations, depending on your architecture: matlabroot\extern\lib\win32\arch matlabroot\extern\lib\win64\arch where arch is microsoft, watcom, lcc, or borland. Version ’GCC_4.2.0’ not found.
8 8-12 Troubleshooting
9 Reference Information Directories Required for Development and Testing (p. 9-2) Path settings for machines where you want to develop and test applications that contain compiled M-code Directories Required for Run-Time Deployment (p. 9-5) Path settings for machines where you want to run applications that were generated with MATLAB Compiler Unsupported Functions (p. 9-8) Functions not supported in standalone mode MATLAB Compiler Licensing (p.
9 Reference Information Directories Required for Development and Testing In this section... “Overview” on page 9-2 “Path for Java Development on All Platforms ” on page 9-2 “Windows Settings for Development and Testing” on page 9-2 “UNIX Settings for Development and Testing” on page 9-3 Overview The following information is for programmers developing applications that use libraries or components that contain compiled M-code.
Directories Required for Development and Testing UNIX Settings for Development and Testing When programming with components that are generated with MATLAB Compiler, use the following commands to add the required platform-specific directories to your dynamic library path. Note For readability, the following commands appear on separate lines, but you must enter each setenv command on one line. Linux setenv LD_LIBRARY_PATH matlabroot/sys/os/glnx86: matlabroot/bin/glnx86: matlabroot/sys/java/jre/glnx86/jre1.
9 Reference Information matlabroot/sys/java/jre/glnxa64/jre1.6.0/lib/amd64: setenv XAPPLRESDIR matlabroot/X11/app-defaults Mac OS X setenv DYLD_LIBRARY_PATH matlabroot/bin/mac: matlabroot/sys/os/mac: /System/Library/Frameworks/JavaVM.framework/JavaVM: /System/Library/Frameworks/JavaVM.framework/Libraries setenv XAPPLRESDIR matlabroot>/X11/app-defaults You can then run the compiled applications on your development machine to test them.
Directories Required for Run-Time Deployment Directories Required for Run-Time Deployment In this section... “Path for Java Applications on All Platforms” on page 9-5 “Windows Path for Run-Time Deployment” on page 9-5 “UNIX Paths for Run-Time Deployment” on page 9-6 Path for Java Applications on All Platforms When your users run applications that contain compiled M-code, you must instruct them to set the path so that the system can find the MCR.
9 Reference Information UNIX Paths for Run-Time Deployment Note For readability, the following commands appear on separate lines, but you must enter each setenv command on one line. Linux setenv LD_LIBRARY_PATH mcr_root/version/run time/glnx86: mcr_root/version/sys/os/glnx86: mcr_root/version/sys/java/jre/glnx86/jre1.6.0/lib/i386/native_threads: mcr_root/version/sys/java/jre/glnx86/jre1.6.0/lib/i386/server: mcr_root/version/sys/java/jre/glnx86/jre1.6.
Directories Required for Run-Time Deployment setenv XAPPLRESDIR mcr_root/version/X11/app-defaults Mac OS X setenv DYLD_LIBRARY_PATH mcr_root/version/run time/mac: mcr_root/version/sys/os/mac: mcr_root/version/bin/mac: /System/Library/Frameworks/JavaVM.framework/JavaVM: /System/Library/Frameworks/JavaVM.
9 Reference Information Unsupported Functions Some functions are not supported in standalone mode; that is, you cannot compile them with MATLAB Compiler. These functions are in the following categories: • Functions that print or report MATLAB code from a function, for example, the MATLAB help function or debug functions, will not work. • Simulink® functions, in general, will not work. • Functions that require a command line, for example, the MATLAB lookfor function, will not work.
Unsupported Functions List of Unsupported Functions (Continued) dbstatus dbstep dbstop dbtype dbup delete_block delete_line depfun doc echo edit fields figure_palette get_param help home inmem keyboard linmod mislocked mlock more munlock new_system open_system pack 9-9
9 Reference Information List of Unsupported Functions (Continued) plotbrowser plottools propedit propertyeditor publish rehash set_param sim simget simset sldebug type 9-10
MATLAB Compiler Licensing MATLAB Compiler Licensing In this section... “Deployed Applications” on page 9-11 “Using MATLAB Compiler Licenses for Development” on page 9-11 Deployed Applications Before you deploy applications or components to your users, you should be aware of the license conditions. Consult the Deployment Addendum in the MathWorks License Agreement at www.mathworks.com/license for terms and conditions of deployment.
9 Reference Information the user gets a new 30-minute allotment. When the 30-minute interval has elapsed, if a different user requests MATLAB Compiler, the new user gets the next 30-minute interval. When a user requests MATLAB Compiler and a license is not available, the user receives the message Error: Could not check out a Compiler License. This message is given when no licenses are available. As long as licenses are available, the user gets the license and no message is displayed.
Using MCRInstaller.exe on the Command Line Using MCRInstaller.exe on the Command Line In this section... “Running MCRInstaller.exe” on page 9-13 “Examples: MCRInstaller.exe Command Line” on page 9-14 Running MCRInstaller.exe When you want to run MCRInstaller.exe without any options or arguments you can use a GUI to install the MCR. This is the best technique for most applications. For more powerful installation options, you can use the command line with the options described in the next table.
9 Reference Information Frequently Used Options for MCRInstaller.exe (Continued) Option Tells InstallShield to... /s Run the installation in silent mode based on the responses contained in a default response file. There must be a space after /s. /v Pass command-line options and values of public properties to Msiexec.exe. Make sure there is no space after /v.
Using MCRInstaller.exe on the Command Line The following command: MCRInstaller.exe /v"/L*v \"C:\log.txt\"" causes the installer to create a verbose log of the install process in log.txt in C:.
9 9-16 Reference Information
10 Functions — By Category Pragmas (p. 10-2) Directives to MATLAB Compiler Command-Line Tools (p.
10 Functions — By Category Pragmas %#external Pragma to call arbitrary C/C++ functions from M-code %#function Pragma to help MATLAB Compiler locate functions called through feval, eval, or Handle Graphics® callback Command-Line Tools 10-2 builder2prj Convert project files with suffixes .cbl, .nbl, and .mxl to .
11 Functions — Alphabetical List %#external %#function builder2prj ctfroot deployprint deploytool isdeployed mbuild mcc
%#external Purpose Pragma to call arbitrary C/C++ functions from M-code Syntax %#external Description The %#external pragma informs MATLAB Compiler that the implementation version of the function (Mlxf) will be hand written and not generated from the M-code. This pragma affects only the single function in which it appears, and any M-function may contain this pragma (local, global, private, or method).
%#function Purpose Pragma to help MATLAB Compiler locate functions called through feval, eval, or Handle Graphics® callback Syntax %#function function1 [function2 ... functionN] %#function object_constructor Description The %#function pragma informs MATLAB Compiler that the specified function(s) will be called through an feval, eval, or Handle Graphics callback.
%#function feval('bar'); feval('foobar'); end %function foo In this example, multiple functions (bar and foobar) are included in the compilation and are called through feval.
builder2prj Purpose Convert project files with suffixes .cbl, .nbl, and .mxl to .prj (deploytool) format Syntax builder2prj builder2prj([project.cbl,project.nbl,project.mxl]) builder2prj([project.cbl,project.nbl,project.mxl], new_project.prj) Description This function converts project files in older formats such as.cbl, .nbl, and .mxl, to a format usable by deploytool (.prj).
builder2prj builder2prj is run, converting the .mxl project to a .prj project. The new project is named renamed_project.prj.
ctfroot Purpose Root directory of application in deployed mode Syntax ctfroot Description root = ctfroot returns a string that is the name of the directory where the CTF file for the deployed application is expanded. To determine the location of various toolbox directories in deployed mode, use the toolboxdir function.
deployprint Purpose Use to print (as substitute for MATLAB print function) when working with deployed Windows applications Syntax deployprint Description In cases where the print command would normally be issued when running MATLAB, use deployprint when working with deployed applications. deployprint is available on all platforms, however it is only required on Windows.
deployprint • Orientation • PrintHeader Note deployprint requires write access to the file system in order to write temporary files.
deploytool Purpose Open GUI for MATLAB Compiler Syntax deploytool Description The deploytool command displays the Deployment Tool window, which is the graphical user interface (GUI) for MATLAB Compiler. See “Using the GUI to Create and Package a Deployable Component” on page 1-6 to get started using the Deployment Tool to create standalone applications and libraries.
isdeployed Purpose Determine whether code is running in deployed or MATLAB mode Syntax x = isdeployed Description x = isdeployed returns true (1) when the function is running in deployed mode and false (0) if it is running in a MATLAB session. If you include this function in an application and compile the application with MATLAB Compiler, the function will return true when the application is run in deployed mode.
mbuild Purpose Compile and link source files into standalone application or shared library Syntax mbuild [option1 ... optionN] sourcefile1 [... sourcefileN] [objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN] [exportfile1 ... exportfileN] Note Supported types of source files are .c, .cpp, .idl, .rc. To specify IDL source files to be compiled with the Microsoft Interface Definition Language (MIDL) Compiler, add .idl to the mbuild command line. To specify a DEF file, add .
mbuild Option Description -D Define a symbol name to the C preprocessor. Equivalent to a #define directive in the source. -D= Define a symbol name and value to the C preprocessor. Equivalent to a #define directive in the source. -f Specify location and name of options file to use. Overrides the mbuild default options file search mechanism. -g Create an executable containing additional symbolic information for use in debugging.
mbuild 11-14 Option Description -n No execute mode. Print out any commands that mbuild would otherwise have executed, but do not actually execute any of them. -O Optimize the object code. Optimization is enabled by default and by including this option on the command line. If the -g option appears without the -O option, optimization is disabled. -outdir Place all output files in directory . -output Create an executable named .
mbuild Option Description -v Verbose mode. Print the values for important internal variables after the options file is processed and all command line arguments are considered. Prints each compile step and final link step fully evaluated. = Supplement or override an options file variable for variable . This option is processed after the options file is processed and all command line arguments are considered.
mbuild Note MBUILD can also create shared libraries from C source code. If a file with the extension .exports is passed to MBUILD, a shared library is built. The .exports file must be a text file, with each line containing either an exported symbol name, or starting with a # or * in the first column (in which case it is treated as a comment line). If multiple .exports files are specified, all symbol names in all specified .exports files are exported.
mcc Purpose Invoke MATLAB Compiler Syntax mcc [-options] mfile1 Description mcc is the MATLAB command that invokes MATLAB Compiler. You can issue the mcc command either from the MATLAB command prompt (MATLAB mode) or the DOS or UNIX command line (standalone mode). [mfile2 ... mfileN] [C/C++file1 ...
mcc are added to the CTF archive, and the directory subtree in testdir is preserved in the CTF archive. If a wildcard pattern is included in the filename, only the files in the directory that match the pattern are added to the CTF archive and subdirectories of the given path are not processed recursively. For example: mcc -m hello.m -a ./testdir/* In this example, all files in ./testdir are added to the CTF archive and subdirectories under ./testdir are not processed recursively. mcc -m hello.m -a .
mcc The -a switch also creates a .auth file for authorization purposes. It ensures that the executable looks for the DLL- and H-files in the exe_mcr\exe folder. -b Generate Excel-Compatible Formula Function Generate a Visual Basic file (.bas) containing the Microsoft Excel Formula Function interface to the COM object generated by MATLAB Compiler. When imported into the workbook Visual Basic code, this code allows the MATLAB function to be seen as a cell formula function.
mcc Note Do not terminate the output directory with a slash or backslash, e.g., use mcc -md C:\TEMP test.m. Do not use mcc -md C:\TEMP\ test.m. -e Suppress MS-DOS Command Window Suppress appearance of the MS-DOS command window when generating a standalone application. Use -e in place of the -m option. This option is available for Windows only. Use with -R option to generate error logging as such: mcc -e -R -logfile,"bar.txt" -v foo.
mcc to specify project_name as the project file name when calling mcc. This option enables the .prj file, along with all of its associated settings, to be fed back to mcc. Project files created using either mcc or deploytool are eligible to use this option. When using -F, no other arguments may be invoked against mcc. -g Generate Debugging Information Include debugging symbol information for the C/C++ code generated by MATLAB Compiler.
mcc -m Generate a Standalone Application Macro to produce a standalone application. This macro is equivalent to -W main -T link:exe Use the -e option instead of the -m option to generate a standalone application while suppressing the appearance of the MS-DOS Command Window. -M Direct Pass Through Define compile-time options. Use -M string to pass string directly to the mbuild script. This provides a useful mechanism for defining compile-time options, e.g., -M "-Dmacro=value".
mcc the relative ordering of the included directories. All subdirectories of the included directories that appear on the original path are also included. In addition, the -N option retains all directories that the user has included on the path that are not under matlabroot/toolbox. -o Specify Output Name Specify the name of the final executable (standalone applications only). Use -o outputfile to name the final executable output of MATLAB Compiler.
mcc the directory is added to the head of the path, as it normally would be with -I. -R Run-Time Provide MCR run-time options. Use the syntax -R option to provide either of these run-time options. Option Description -nojvm Do not use the Java Virtual Machine (JVM). -nojit Do not use the MATLAB JIT (binary code generation used to accelerate M-file execution). Note The -R option is available only for standalone applications.
mcc Target Description codegen Generates a C/C++ wrapper file. The default is codegen. compile:exe Same as codegen plus compiles C/C++ files to object form suitable for linking into a standalone application. compile:lib Same as codegen plus compiles C/C++ files to object form suitable for linking into a shared library/DLL. link:exe Same as compile:exe plus links object files into a standalone application. link:lib Same as compile:lib plus links object files into a shared library/DLL.
mcc Syntax Description -w list Generates a table that maps to warning message for use with enable, disable, and error. Appendix B, “Error and Warning Messages” lists the same information. -w enable Enables complete warnings. -w disable[:] Disables specific warning associated with . Appendix B, “Error and Warning Messages”, lists the valid values. Leave off the optional to apply the disable action to all warnings.
mcc appropriate global variable definitions. This table shows the valid options. Type Description main Produces a POSIX shell main() function. lib: Creates a C interface and produces an initialization and termination function for use when compiling this compiler generated code into a larger application. This option also produces a header file containing prototypes for all public functions in all M-files specified. becomes the base (file) name for the generated C/C++ and header file.
mcc -z path to specify path to use for the compiler libraries and include files instead of the path returned by matlabroot. -? Help Message Display MATLAB Compiler help at the command prompt. Linux mcc Cache Management Command Options Examples The Bourne shell front-end interface to the MATLAB Compiler uses a cache file to speed execution. The cache file contains precomputed values of critical environment variables.
mcc Make a standalone executable for myfun.m, but look for myfun.m in the /files/source directory and put the resulting C files and in the /files/target directory. mcc -m -I /files/source -d /files/target myfun Make the standalone myfun1 from myfun1.m and myfun2.m (using one mcc call). mcc -m myfun1 myfun2 Make a shared/dynamically linked library called liba from a0.m and a1.m.
mcc 11-30
12 Limitations and Restrictions Limitations About What May Be Compiled (p.
12 Limitations and Restrictions Limitations About What May Be Compiled In this section...
Limitations About What May Be Compiled Note See “Unsupported Functions” on page 9-8 for a complete list of functions that cannot be compiled. MATLAB Code MATLAB Compiler 4 supports much of the functionality of MATLAB. However, there are some limitations and restrictions that you should be aware of. This version of MATLAB Compiler cannot create interfaces for script M-files (See “Converting Script M-Files to Function M-Files” on page 5-19 for further details.
12 Limitations and Restrictions Workaround There are several ways to eliminate this error. • Using the %#function pragma and specifying callbacks as strings • Specifying callbacks with function handles • Using the -a option Specifying Callbacks as Strings. Create a list of all the functions that are specified only in callback strings and pass these functions using separate %#function pragma statements.
Limitations About What May Be Compiled For more information on specifying the value of a callback, see Specifying the Value of Callback Function Properties in the MATLAB Programming documentation. Using the -a Option. Instead of using the %#function pragma, you can specify the name of the missing M-file on MATLAB Compiler command line using the -a option.
12 Limitations and Restrictions Cannot Create the Output File If you receive the error Can't create the output file filename there are several possible causes to consider: • Lack of write permission for the directory where MATLAB Compiler is attempting to write the file (most likely the current working directory). • Lack of free disk space in the directory where MATLAB Compiler is attempting to write the file (most likely the current working directory).
Limitations About What May Be Compiled Older Neural Networks Not Deployable with MATLAB Compiler Loading networks saved from older Neural Network Toolbox versions requires some initialization routines that are not deployable. Therefore, these networks cannot be deployed without first being updated. For example, deploying with Neural Network Toolbox 5.0.1 (2006b) and MATLAB Compiler 4.5 (R2006b) yields the following errors at run-time: ??? Error using ==> network.subsasgn "layers{1}.
12 12-8 Limitations and Restrictions
A MATLAB Compiler Quick Reference Common Uses of MATLAB Compiler (p. A-2) Summary of how to use MATLAB Compiler mcc (p.
A MATLAB Compiler Quick Reference Common Uses of MATLAB Compiler In this section... “Create a Standalone Application” on page A-2 “Create a Library” on page A-2 Create a Standalone Application Example 1 To create a standalone application from mymfile.m, use mcc -m mymfile Example 2 To create a standalone application from mymfile.m, look for mymfile.
Common Uses of MATLAB Compiler Example 2 To create a C shared library called library_one from foo1.m and foo2.m, use mcc -W lib:library_one -T link:lib foo1 foo2 Note You can add the -g option to any of these for debugging purposes.
A MATLAB Compiler Quick Reference mcc Bold entries in the Comment/Options column indicate default values. Option Description Comment/Options -a filename Add filename to the CTF archive. None -b Generate Excel compatible formula function. Requires MATLAB Builder for Excel -B Replace -B filename on the filename[:arg[,arg]] mcc command line with the contents of filename. The file should contain only mcc command-line options.
mcc Option Description Comment/Options -I directory Add directory to search path for M-files. MATLAB path is automatically included when running from MATLAB, but not when running from a DOS/UNIX shell. -l Macro to create a function library. -W lib -T link:lib Macro to generate a C standalone application. -W main -T link:exe -M string Pass string to mbuild. Use to define compile-time options. -N Clear the path of all but a minimal, required set of directories.
A MATLAB Compiler Quick Reference Option Description Comment/Options -w option Display warning messages. option = list level level:string where level = disable enable error A-6 -W type Control the generation of function wrappers. type = main cpplib: lib: none com:compname,clname,version -Y licensefile Use licensefile when checking out a MATLAB Compiler license. None -z path Specify path for library and include files. None -? Display help message.
B Error and Warning Messages About Error and Warning Messages (p. B-2) How to use the error and warning messages guide Compile-Time Errors (p. B-3) Error messages generated at compile time Warning Messages (p. B-7) User-controlled warnings generated by MATLAB Compiler depfun Errors (p.
B Error and Warning Messages About Error and Warning Messages This appendix lists and describes error messages and warnings generated by MATLAB Compiler. Compile-time messages are generated during the compile or link phase. It is useful to note that most of these compile-time error messages should not occur if MATLAB can successfully execute the corresponding M-file.
Compile-Time Errors Compile-Time Errors Error: An error occurred while shelling out to mex/mbuild (error code = errorno). Unable to build (specify the -v option for more information). MATLAB Compiler reports this error if mbuild or mex generates an error. Error: An error occurred writing to file "filename": reason. The file could not be written. The reason is provided by the operating system. For example, you may not have sufficient disk space available to write the file.
B Error and Warning Messages Error: File: filename Line: # Column: # A variable cannot be made storageclass1 after being used as a storageclass2. You cannot change a variable’s storage class (global/local/persistent). Even though MATLAB allows this type of change in scope, MATLAB Compiler does not. Error: Found illegal whitespace character in command line option: "string". The strings on the left and right side of the space should be separate arguments to MCC.
Compile-Time Errors Error: The argument after the -option option must contain a colon. The format for this argument requires a colon. For more information, see Chapter 10, “Functions — By Category”, or type mcc -? at the command prompt. Error: The environment variable MATLAB must be set to the MATLAB root directory. On UNIX, the MATLAB and LM_LICENSE_FILE variables must be set. The mcc shell script does this automatically when it is called the first time.
B Error and Warning Messages Error: Unknown warning enable/disable string: warningstring. -w enable:, -w disable:, and -w error: require you to use one of the warning string identifiers listed in “Warning Messages” on page B-7. Error: Unrecognized option: -option. The option is not a valid option. See Chapter 10, “Functions — By Category” for a complete list of valid options for MATLAB Compiler, or type mcc -? at the command prompt.
Warning Messages Warning Messages This section lists the warning messages that MATLAB Compiler can generate. Using the -w option for mcc, you can control which messages are displayed. Each warning message contains a description and the warning message identifier string (in parentheses) that you can enable or disable with the -w option.
B Error and Warning Messages Warning: The file filename was repeated on MATLAB Compiler command line. (repeated_file) This warning occurs when the same filename appears more than once on the compiler command line. For example: mcc -m sample.m sample.m % Will generate the warning Warning: The name of a shared library should begin with the letters "lib". "libraryname" doesn’t. (missing_lib_sentinel) This warning is generated if the name of the specified library does not begin with the letters “lib”.
Warning Messages Note A link error is produced if a call to this function is made from standalone code. DEMO Compiler license. The generated application will expire 30 days from today, on date. (demo_license) This warning displays the date that the deployed application will expire. This warning is enabled.
B Error and Warning Messages depfun Errors In this section... “About depfun Errors” on page B-10 “MCR/Dispatcher Errors” on page B-10 “XML Parser Errors” on page B-10 “depfun-Produced Errors” on page B-11 About depfun Errors MATLAB Compiler uses a dependency analysis (depfun) to determine the list of necessary files to include in the CTF package. If this analysis encounters a problem, depfun displays an error.
depfun Errors Where is a message returned by the XML parser. If this error occurs, report it to Technical Support at The MathWorks at http://www.mathworks.com/contact_TS.html. depfun-Produced Errors These errors originate directly from depfun. depfun Error: Internal error. This error occurs if an internal error is encountered that is unexpected, for example, a memory allocation error or a system error of some kind. This error is never user generated.
B Error and Warning Messages B-12
C C++ Utility Library Reference Primitive Types (p. C-2) Primitive types that can be stored in a MATLAB array Utility Classes (p. C-3) Utility classes used by the mwArray API mwString Class (p. C-4) String class used by the API to pass string data as output mwException Class (p. C-20) Exception type used by the mwArray API and the C++ interface functions mwException Class Functions (p. C-21) Exception handling functions that report errors that occur during array processing mwArray Class (p.
C C++ Utility Library Reference Primitive Types The mwArray API supports all primitive types that can be stored in a MATLAB array. This table lists all the types.
Utility Classes Utility Classes The following are C++ utility classes: • “mwString Class” on page C-4 • “mwException Class” on page C-20 • “mwArray Class” on page C-29 C-3
C C++ Utility Library Reference mwString Class In this section... “About mwString” on page C-4 “Constructors” on page C-4 “Methods” on page C-4 “Operators” on page C-4 About mwString The mwString class is a simple string class used by the mwArray API to pass string data as output from certain methods.
mwString Class • bool operator>(const mwString& str) const • bool operator>=(const mwString& str) const • friend std::ostream& operator<<(std::ostream& os, const mwString& str) C-5
mwString() Purpose C++ Syntax C-6 Construct empty string #include "mclcppclass.h" mwString str; Arguments None Return Value None Description Use this constructor to create an empty string.
mwString(const char* str) Purpose C++ Syntax Arguments Construct new string and initialize strings data with supplied char buffer #include "mclcppclass.h" mwString str("This is a string"); str NULL-terminated char buffer to initialize the string. Return Value None Description Use this constructor to create a string from a NULL-terminated char buffer.
mwString(const mwString& str) Purpose C++ Syntax Arguments Copy constructor for mwString #include "mclcppclass.h" mwString str("This is a string"); mwString new_str(str); // new_str contains a copy of the // characters in str. str mwString to be copied. C-8 Return Value None Description Use this constructor to create an mwString that is a copy of an existing one. Constructs a new string and initializes its data with the supplied mwString.
int Length() const Purpose C++ Syntax Return number of characters in string #include "mclcppclass.h" mwString str("This is a string"); int len = str.Length(); // len should be 16. Arguments None Return Value The number of characters in the string. Description Use this method to get the length of an mwString. The value returned does not include the terminating NULL character.
operator const char* () const Purpose C++ Syntax C-10 Return pointer to internal buffer of string #include "mclcppclass.h" mwString str("This is a string"); const char* pstr = (const char*)str; Arguments None Return Value A pointer to the internal buffer of the string. Description Use this operator to get direct read-only access to the string’s data buffer.
mwString& operator=(const mwString& str) Purpose C++ Syntax Arguments mwString assignment operator #include "mclcppclass.h" mwString str("This is a string"); mwString new_str = str; // new_str contains a copy of // the data in str. str String to make a copy of. Return Value A reference to the invoking mwString object. Description Use this operator to copy the contents of one string into another.
mwString& operator=(const char* str) Purpose C++ Syntax Arguments mwString assignment operator #include "mclcppclass.h" const char* pstr = "This is a string"; mwString str = pstr; // str contains copy of data in pstr. str char buffer to make copy of. C-12 Return Value A reference to the invoking mwString object. Description Use this operator to copy the contents of a NULL-terminated buffer into an mwString.
bool operator==(const mwString& str) const Purpose C++ Syntax Arguments Test two mwStrings for equality #include mwString mwString bool ret "mclcppclass.h" str("This is a string"); str2("This is another string"); = (str == str2);// ret should have value of false. str String to compare. Return Value The result of the comparison. Description Use this operator to test two strings for equality.
bool operator!=(const mwString& str) const Purpose C++ Syntax Arguments Test two mwStrings for inequality #include mwString mwString bool ret "mclcppclass.h" str("This is a string"); str2("This is another string"); = (str != str2); // ret should have value of // true. str String to compare. C-14 Return Value The result of the comparison. Description Use this operator to test two strings for inequality.
bool operator<(const mwString& str) const Purpose C++ Syntax Arguments Compare input string with this string and return true if this string is lexicographically less than input string #include mwString mwString bool ret "mclcppclass.h" str("This is a string"); str2("This is another string"); = (str < str2); // ret should have a value // of true. str String to compare. Return Value The result of the comparison. Description Use this operator to test two strings for order.
bool operator<=(const mwString& str) const Purpose C++ Syntax Arguments Compare input string with this string and return true if this string is lexicographically less than or equal to input string #include mwString mwString bool ret "mclcppclass.h" str("This is a string"); str2("This is another string"); = (str <= str2); // ret should have value // of true. str String to compare. C-16 Return Value The result of the comparison. Description Use this operator to test two strings for order.
bool operator>(const mwString& str) const Purpose C++ Syntax Arguments Compare input string with this string and return true if this string is lexicographically greater than input string #include mwString mwString bool ret "mclcppclass.h" str("This is a string"); str2("This is another string"); = (str > str2); // ret should have value // of false. str String to compare. Return Value The result of the comparison. Description Use this operator to test two strings for order.
bool operator>=(const mwString& str) const Purpose C++ Syntax Arguments Compare input string with this string and return true if this string is lexicographically greater than or equal to input string #include mwString mwString bool ret "mclcppclass.h" str("This is a string"); str2("This is another string"); = (str >= str2);//ret should have value of false. str String to compare. C-18 Return Value The result of the comparison. Description Use this operator to test two strings for order.
friend std::ostream& operator<<(std::ostream& os, const mwString& str) Purpose Copy contents of input string to specified ostream C++ Syntax Arguments #include "mclcppclass.h" #include mwString str("This is a string"); std::cout << str << std::endl; //should print "This is a //string" to standard out. os ostream to copy string to. str String to copy. Return Value The input ostream. Description Use this operator to print the contents of an mwString to an ostream.
C C++ Utility Library Reference mwException Class In this section... “About mwException” on page C-20 “Constructors” on page C-20 “Methods” on page C-20 “Operators” on page C-20 About mwException The mwException class is the basic exception type used by the mwArray API and the C++ interface functions. All errors created during calls to the mwArray API and to MATLAB Compiler generated C++ interface functions are thrown as mwExceptions.
mwException Class Functions mwException Class Functions The following function is in the mwExceptionClass.
mwException() Purpose C++ Syntax C-22 Construct new mwException with default error message #include "mclcppclass.h" throw mwException(); Arguments None Return Value None Description Use this constructor to create an mwException without specifying an error message.
mwException(const char* msg) Purpose C++ Syntax Arguments Construct new mwException with specified error message #include "mclcppclass.h" try { throw mwException("This is an error"); } catch (const mwException& e) { std::cout << e.what() << std::endl // Displays "This // is an error" to // standard out. } msg Error message. Return Value None Description Use this constructor to create an mwException with a specified error message.
mwException(const mwException& e) Purpose Copy constructor for mwException class C++ Syntax Arguments #include "mclcppclass.h" try { throw mwException("This is an error"); } catch (const mwException& e) { throw mwException(e); // Rethrows same error. } e mwException to create copy of. C-24 Return Value None Description Use this constructor to create a copy of an mwException. The copy will have the same error message as the original.
mwException(const std::exception& e) Purpose Create new mwException from existing std::exception C++ Syntax Arguments #include "mclcppclass.h" try { ... } catch (const std::exception& e) { throw mwException(e); } // Rethrows same error. e std::exception to create copy of. Return Value None Description Use this constructor to create a new mwException and initialize the error message with the error message from the given std::exception.
const char *what() const throw() Purpose C++ Syntax C-26 Return error message contained in this exception #include "mclcppclass.h" try { ... } catch (const std::exception& e) { std::cout << e.what() << std::endl; // Displays error // message to // standard out. } Arguments None Return Value A pointer to a NULL-terminated character buffer containing the error message. Description Use this method to retrieve the error message from an mwException.
mwException& operator=(const mwException& e) Purpose Assignment operator for mwException class C++ Syntax Arguments #include "mclcppclass.h" try { ... } catch (const mwException& e) { mwException e2 = e; throw e2; } e mwException to create copy of. Return Value A reference to the invoking mwException. Description Use this operator to create a copy of an mwException. The copy will have the same error message as the original.
mwException& operator=(const std::exception& e) Purpose Assignment operator for mwException class C++ Syntax Arguments #include "mclcppclass.h" try { ... } catch (const std::exception& e) { mwException e2 = e; throw e2; } e std::exception to initialize copy with. C-28 Return Value A reference to the invoking mwException. Description Use this operator to create a copy of an std::exception. The copy will have the same error message as the original.
mwArray Class mwArray Class In this section... “About mwArray” on page C-29 “Constructors” on page C-29 “Methods” on page C-30 “Operators” on page C-31 “Static Methods” on page C-31 About mwArray Use the mwArray class to pass input/output arguments to MATLAB Compiler generated C++ interface functions. This class consists of a thin wrapper around a MATLAB array. The mwArray class provides the necessary constructors, methods, and operators for array creation and initialization, as well as simple indexing.
C C++ Utility Library Reference • mwArray(mwSize num_dims, const mwSize* dims, int num_fields, const char** fieldnames) • mwArray(const mwArray& arr) • mwArray( re) • mwArray( re, im) Methods • mwArray Clone() const • mwArray SharedCopy() const • mwArray Serialize() const • mxClassID ClassID() const • int ElementSize() const • size_t ElementSize() const • mwSize NumberOfElements() const • mwSize NumberOfNonZeros() const • mwSize MaximumNonZeros() const • mwSize NumberOfDimensions() co
mwArray Class • mwString ToString() const • mwArray RowIndex() const • mwArray ColumnIndex() const • void MakeComplex() • mwArray Get(mwSize num_indices, ...) • mwArray Get(const char* name, mwSize num_indices, ...
C C++ Utility Library Reference • static double GetNaN() • static double GetEps() • static double GetInf() • static bool IsFinite(double x) • static bool IsInf(double x) • static bool IsNaN(double x) C-32
mwArray Class Functions mwArray Class Functions The following function is in the mwarray Class.
mwArray() Purpose C++ Syntax C-34 Construct empty array of type mxDOUBLE_CLASS #include "mclcppclass.h" mwArray a; Return Value None Description Use this constructor to create an empty array of type mxDOUBLE_CLASS.
mwArray(mxClassID mxID) Purpose C++ Syntax Construct empty array of specified type #include "mclcppclass.h" mwArray a(mxDOUBLE_CLASS); Return Value None Description Use this constructor to create an empty array of the specified type. You can use any valid mxClassID. See the External Interfaces documentation for more information on mxClassID.
mwArray(mwSize num_rows, mwSize num_cols, mxClassID mxID, mxComplexity cmplx = mxREAL) Purpose C++ Syntax Arguments Construct 2-D matrix of specified type and dimensions #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); mwArray b(3, 3, mxSINGLE_CLASS, mxCOMPLEX); mwArray c(2, 3, mxCELL_CLASS); num_rows The number of rows. num_cols The number of columns. mxID The data type type of the matrix. cmplx The complexity of the matrix (numeric types only).
mwArray(mwSize num_dims, const mwSize* dims, mxClassID mxID, mxComplexity cmplx = mxREAL) Purpose C++ Syntax Arguments Construct n-dimensional array of specified type and dimensions #include "mclcppclass.h" int dims[3] = {2,3,4}; mwArray a(3, dims, mxDOUBLE_CLASS); mwArray b(3, dims, mxSINGLE_CLASS, mxCOMPLEX); mwArray c(3, dims, mxCELL_CLASS); num_dims Size of the dims array. dims Dimensions of the array. mxID The data type type of the matrix. cmplx The complexity of the matrix (numeric types only).
mwArray(const char* str) Purpose C++ Syntax Arguments Construct character array from supplied string #include "mclcppclass.h" mwArray a("This is a string"); str NULL-terminated string C-38 Return Value None Description Use this constructor to create a 1-by-n array of type mxCHAR_CLASS, with n = strlen(str), and initialize the array’s data with the characters in the supplied string.
mwArray(mwSize num_strings, const char** str) Purpose Construct character matrix from list of strings C++ Syntax Arguments #include "mclcppclass.h" const char* str[] = {"String1", "String2", "String3"}; mwArray a(3, str); num_strings Number of strings in the input array str Array of NULL-terminated strings Return Value None Description Use this constructor to create a matrix of type mxCHAR_CLASS, and initialize the array’s data with the characters in the supplied strings.
mwArray(mwSize num_rows, mwSize num_cols, int num_fields, const char** fieldnames) Purpose C++ Syntax Arguments Construct 2-D MATLAB structure matrix of specified dimensions and field names #include "mclcppclass.h" const char* fields[] = {"a", "b", "c"}; mwArray a(2, 2, 3, fields); num_rows Number of rows in the struct matrix. num_cols Number of columns in the struct matrix. num_fields Number of fields in the struct matrix. fieldnames Array of NULL-terminated strings representing the field names.
mwArray(mwSize num_dims, const mwSize* dims, int num_fields, const char** fieldnames) Purpose C++ Syntax Arguments Construct n-dimensional MATLAB structure array of specified dimensions and field names #include "mclcppclass.
mwArray(const mwArray& arr) Purpose C++ Syntax Arguments mwArray copy constructor. Constructs new array from existing one #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); mwArray b(a); arr mwArray to copy C-42 Return Value None Description Use this constructor to create a copy of an existing array. The new array contains a deep copy of the input array.
mwArray( re) Purpose Construct real scalar array of type of the input argument and initialize data with input argument’s value C++ Syntax Arguments #include "mclcppclass.h" double x = 5.0; mwArray a(x); // Creates 1X1 double array with value 5.0 re Scalar value to initialize array with Return Value None Description Use this constructor to create a real scalar array.
mwArray( re, im) Purpose Construct complex scalar array of type of input arguments and initialize real and imaginary parts of data with input argument’s values C++ Syntax Arguments #include "mclcppclass.h" double re = 5.0; double im = 10.
mwArray Clone() const Purpose C++ Syntax Return new array representing deep copy of array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); mwArray b = a.Clone(); Arguments None Return Value New mwArray representing a deep copy of the original. Description Use this method to create a copy of an existing array. The new array contains a deep copy of the input array.
mwArray SharedCopy() const Purpose C++ Syntax C-46 Return new array representing shared copy of array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); mwArray b = a.SharedCopy(); Arguments None Return Value New mwArray representing a reference counted version of the original. Description Use this method to create a shared copy of an existing array. The new array and the original array both point to the same data.
mwArray Serialize() const Purpose C++ Syntax Serialize underlying array into byte array, and return this data in new array of type mxUINT8_CLASS #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); mwArray s = a.Serialize(); Arguments None Return Value New mwArray of type mxUINT8_CLASS containing the serialized data. Description Use this method to serialize an array into bytes. A 1-by-n numeric matrix of type mxUINT8_CLASS is returned containing the serialized data.
mxClassID ClassID() const Purpose C++ Syntax C-48 Return type of array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); mxClassID id = a.ClassID();// Should return mxDOUBLE_CLASS Arguments None Return Value The mxClassID of the array. Description Use this method to determine the type of the array. Consult the External Interfaces documentation for more information on mxClassID.
int ElementSize() const Purpose C++ Syntax Return size in bytes of element of array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); int size = a.ElementSize();// Should return sizeof(double) Arguments None Return Value The size in bytes of an element of this type of array. Description Use this method to determine the size in bytes of an element of array type. Note If you define MX_COMPAT_32_OFF, this method is defined as size_t ElementSize() const.
size_t ElementSize() const Purpose C++ Syntax Return size in bytes of an element of array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); int size = a.ElementSize();// Should return sizeof(double) Arguments None Return Value The size in bytes of an element of this type of array. Description Use this method to determine the size in bytes of an element of array type. Note If you do not define MX_COMPAT_32_OFF, this method is defined as size-t ElementSize() const.
mwSize NumberOfElements() const Purpose C++ Syntax Return number of elements in array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); int n = a.NumberOfElements();// Should return 4 Arguments None Return Value Number of elements in array. Description Use this method to determine the total size of the array.
mwSize NumberOfNonZeros() const Purpose C++ Syntax Return number of nonzero elements for sparse array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); int n = a.NumberOfNonZeros();// Should return 4 Arguments None Return Value Actual number of nonzero elements in array. Description Use this method to determine the size of the of the array’s data. If the underlying array is not sparse, this returns the same value as NumberOfElements().
mwSize MaximumNonZeros() const Purpose C++ Syntax Return maximum number of nonzero elements for sparse array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); int n = a.MaximumNonZeros();// Should return 4 Arguments None Return Value Number of allocated nonzero elements in array. Description Use this method to determine the allocated size of the of the array’s data. If the underlying array is not sparse, this returns the same value as NumberOfElements().
mwSize NumberOfDimensions() const Purpose C++ Syntax C-54 Return number of dimensions in array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); int n = a.NumberOfDimensions();// Should return 2 Arguments None Return Value Number of dimensions in array. Description Use this method to determine the dimensionality of the array.
int NumberOfFields() const Purpose C++ Syntax Return number of fields in struct array #include "mclcppclass.h" const char* fields[] = {"a", "b", "c"}; mwArray a(2, 2, 3, fields); int n = a.NumberOfFields(); // Should return 3 Arguments None Return Value Number of fields in the array. Description Use this method to determine the number of fields in a struct array. If the underlying array is not of type struct, zero is returned.
mwString GetFieldName(int index) Purpose C++ Syntax Arguments Return string representing name of (zero-based) field in struct array #include "mclcppclass.h" const char* fields[] = {"a", "b", "c"}; mwArray a(2, 2, 3, fields); mwString tempname = a.GetFieldName(1); const char* name = (const char*)tempname; // Should // return "b" Index Zero-based field number C-56 Return Value mwString containing the field name. Description Use this method to determine the name of a given field in a struct array.
mwArray GetDimensions() const Purpose C++ Syntax Return array of type mxINT32_CLASS representing dimensions of array #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); mwArray dims = a.GetDimensions(); Arguments None Return Value mwArray type mxINT32_CLASS containing the dimensions of the array. Description Use this method to determine the size of each dimension in the array. The size of the returned array is 1-by-NumberOfDimensions().
bool IsEmpty() const Purpose C++ Syntax C-58 Return true if underlying array is empty #include "mclcppclass.h" mwArray a; bool b = a.IsEmpty(); // Should return true Arguments None Return Value Boolean indicating if the array is empty. Description Use this method to determine if an array is empty.
bool IsSparse() const Purpose C++ Syntax Return true if underlying array is sparse #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); bool b = a.IsSparse(); // Should return false Arguments None Return Value Boolean indicating if the array is sparse. Description Use this method to determine if an array is sparse.
bool IsNumeric() const Purpose C++ Syntax C-60 Return true if underlying array is numeric #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); bool b = a.IsNumeric(); // Should return true. Arguments None Return Value Boolean indicating if the array is numeric. Description Use this method to determine if an array is numeric.
bool IsComplex() const Purpose C++ Syntax Return true if underlying array is complex #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS, mxCOMPLEX); bool b = a.IsComplex(); // Should return true. Arguments None Return Value Boolean indicating if the array is complex. Description Use this method to determine if an array is complex.
bool Equals(const mwArray& arr) const Purpose C++ Syntax Arguments Test two arrays for equality #include "mclcppclass.h" mwArray a(1, 1, mxDOUBLE_CLASS); mwArray b(1, 1, mxDOUBLE_CLASS); a = 1.0; b = 1.0; bool c = a.Equals(b); // Should return true. arr Array to compare to array C-62 Return Value Boolean value indicating the equality of the two arrays. Description Returns true if the input array is byte-wise equal to this array. This method makes a byte-wise comparison of the underlying arrays.
int CompareTo(const mwArray& arr) const Purpose C++ Syntax Arguments Compare two arrays for order #include "mclcppclass.h" mwArray a(1, 1, mxDOUBLE_CLASS); mwArray b(1, 1, mxDOUBLE_CLASS); a = 1.0; b = 1.0; int n = a.CompareTo(b); // Should return 0 arr Array to compare to this array Return Value Returns a negative integer, zero, or a positive integer if this array is less than, equal to, or greater than the specified array. Description Compares this array with the specified array for order.
int HashCode() const Purpose C++ Syntax C-64 Return hash code for array #include "mclcppclass.h" mwArray a(1, 1, mxDOUBLE_CLASS); int n = a.HashCode(); Arguments None Return Value An integer value representing a unique hash code for the array. Description This method constructs a unique hash value form the underlying bytes in the array. Therefore, arrays of different types will have different hash codes, even if they are initialized with the same data.
mwString ToString() const Purpose C++ Syntax Return string representation of underlying array #include #include "mclcppclass.h" mwArray a(1, 1, mxDOUBLE_CLASS, mxCOMPLEX); a.Real() = 1.0; a.Imag() = 2.0; printf("%s\n", (const char*)(a.ToString()));// Should print // "1 + 2i" on // screen. Arguments None Return Value An mwString containing the string representation of the array. Description This method returns a string representation of the underlying array.
mwArray RowIndex() const Purpose C++ Syntax C-66 Return array containing row indices of each element in array #include #include "mclcppclass.h" mwArray a(1, 1, mxDOUBLE_CLASS); mwArray rows = a.RowIndex(); Arguments None Return Value An mwArray containing the row indices. Description Returns an array of type mxINT32_CLASS representing the row indices (first dimension) of this array.
mwArray ColumnIndex() const Purpose C++ Syntax Return array containing column indices of each element in array #include "mclcppclass.h" mwArray a(1, 1, mxDOUBLE_CLASS); mwArray rows = a.ColumnIndex(); Arguments None Return Value An mwArray containing the column indices. Description Returns an array of type mxINT32_CLASS representing the column indices (second dimension) of this array.
void MakeComplex() Purpose C++ Syntax C-68 Convert real numeric array to complex #include "mclcppclass.h" double rdata[4] = {1.0, 2.0, 3.0, 4.0}; double idata[4] = {10.0, 20.0, 30.0, 40.0}; mwArray a(2, 2, mxDOUBLE_CLASS); a.SetData(rdata, 4); a.MakeComplex(); a.Imag().SetData(idata, 4); Arguments None Return Value None Description Use this method to convert a numeric array that has been previously allocated as real to complex.
mwArray Get(mwSize num_indices, ...) Purpose C++ Syntax Arguments Return single element at specified 1-based index #include "mclcppclass.h" double data[4] = {1.0, 2.0, 3.0, 4.0}; double x; mwArray a(2, 2, mxDOUBLE_CLASS); a.SetData(data, 4); x = a.Get(1,1); // x = 1.0 x = a.Get(2, 1, 2); // x = 3.0 x = a.Get(2, 2, 2); // x = 4.0 num_indices Number of indices passed in ... Comma-separated list of input indices. Number of items must equal num_indices.
mwArray Get(const char* name, mwSize num_indices, ...) Purpose C++ Syntax Return single element at specified field name and 1-based index in struct array #include "mclcppclass.h" const char* fields[] = {"a", "b", "c"}; mwArray a(1, 1, 3, fields); mwArray b = a.Get("a", 1, 1); mwArray b = a.Get("b", 2, 1, 1); Arguments // b=a.a(1) // b=a.b(1,1) name NULL-terminated string containing the field name to get. num_indices Number of indices passed in. ... Comma-separated list of input indices.
mwArray Get(const char* name, mwSize num_indices, ...) mwException is thrown if an invalid number of indices is passed in or if any index is out of bounds.
mwArray GetA(mwSize num_indices, const mwIndex* index) Purpose C++ Syntax Arguments Return single element at specified 1-based index #include "mclcppclass.h" double data[4] = {1.0, 2.0, 3.0, 4.0}; int index[2] = {1, 1}; double x; mwArray a(2, 2, mxDOUBLE_CLASS); a.SetData(data, 4); x = a.GetA(1, index); x = a.GetA(2, index); index[0] = 2; index[1] = 2; x = a.Get(2, index); // x = 1.0 // x = 1.0 // x = 4.
mwArray GetA(const char* name, mwSize num_indices, const mwIndex* index) Purpose C++ Syntax Arguments Return single element at specified field name and 1-based index in struct array #include "mclcppclass.h" const char* fields[] = {"a", "b", "c"}; int index[2] = {1, 1}; mwArray a(1, 1, 3, fields); mwArray b = a.Get("a", 1, index); mwArray b = a.Get("b", 2, index); // b=a.a(1) // b=a.
mwArray GetA(const char* name, mwSize num_indices, const mwIndex* index) thrown if an invalid number of indices is passed in or if any index is out of bounds.
mwArray Real() Purpose C++ Syntax Return mwArray that references real part of complex array #include "mclcppclass.h" double rdata[4] = {1.0, 2.0, 3.0, 4.0}; double idata[4] = {10.0, 20.0, 30.0, 40.0}; mwArray a(2, 2, mxDOUBLE_CLASS, mxCOMPLEX); a.Real().SetData(rdata, 4); a.Imag().SetData(idata, 4); Arguments None Return Value An mwArray referencing the real part of the array. Description Use this method to access the real part of a complex array.
mwArray Imag() Purpose C++ Syntax Return mwArray that references imaginary part of complex array #include "mclcppclass.h" double rdata[4] = {1.0, 2.0, 3.0, 4.0}; double idata[4] = {10.0, 20.0, 30.0, 40.0}; mwArray a(2, 2, mxDOUBLE_CLASS, mxCOMPLEX); a.Real().SetData(rdata, 4); a.Imag().SetData(idata, 4); Arguments None Return Value An mwArray referencing the imaginary part of the array. Description Use this method to access the imaginary part of a complex array.
void Set(const mwArray& arr) Purpose C++ Syntax Arguments Assign shared copy of input array to currently referenced cell for arrays of type mxCELL_CLASS and mxSTRUCT_CLASS #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); mwArray b(2, 2, mxINT16_CLASS); mwArray c(1, 2, mxCELL_CLASS); c.Get(1,1).Set(a); c.Get(1,2).Set(b); // Sets c(1) = a // Sets c(2) = b arr mwArray to assign to currently referenced cell Return Value None Description Use this method to construct cell and struct arrays.
void GetData(* buffer, mwSize len) const Purpose C++ Syntax Arguments Copy array’s data into supplied numeric buffer #include "mclcppclass.h" double rdata[4] = {1.0, 2.0, 3.0, 4.0}; double data_copy[4] ; mwArray a(2, 2, mxDOUBLE_CLASS); a.SetData(rdata, 4); a.GetData(data_copy, 4); buffer Buffer to receive copy len Maximum length of buffer. A maximum of len elements will be copied.
void GetLogicalData(mxLogical* buffer, mwSize len) const Purpose C++ Syntax Arguments Copy array’s data into supplied mxLogical buffer #include "mclcppclass.h" mxLogical data[4] = {true, false, true, false}; mxLogical data_copy[4] ; mwArray a(2, 2, mxLOGICAL_CLASS); a.SetData(data, 4); a.GetData(data_copy, 4); buffer Buffer to receive copy len Maximum length of buffer. A maximum of len elements will be copied. Return Value None Description The data is copied in column-major order.
void GetCharData(mxChar* buffer, mwSize len) const Purpose C++ Syntax Arguments Copy array’s data into supplied mxChar buffer #include "mclcppclass.h" mxChar data[6] = {'H', 'e' , `l' , 'l' , 'o' , '\0'}; mxChar data_copy[6] ; mwArray a(1, 6, mxCHAR_CLASS); a.SetData(data, 6); a.GetData(data_copy, 6); buffer Buffer to receive copy len Maximum length of buffer. A maximum of len elements will be copied. C-80 Return Value None Description The data is copied in column-major order.
void SetData(* buffer, mwSize len) Purpose C++ Syntax Arguments Copy data from supplied numeric buffer into array #include "mclcppclass.h" double rdata[4] = {1.0, 2.0, 3.0, 4.0}; double data_copy[4] ; mwArray a(2, 2, mxDOUBLE_CLASS); a.SetData(rdata, 4); a.GetData(data_copy, 4); buffer Buffer containing data to copy len Maximum length of buffer. A maximum of len elements will be copied.
void SetLogicalData(mxLogical* buffer, mwSize len) Purpose C++ Syntax Arguments Copy data from supplied mxLogical buffer into array #include "mclcppclass.h" mxLogical data[4] = {true, false, true, false}; mxLogical data_copy[4] ; mwArray a(2, 2, mxLOGICAL_CLASS); a.SetData(data, 4); a.GetData(data_copy, 4); buffer Buffer containing data to copy len Maximum length of buffer. A maximum of len elements will be copied. C-82 Return Value None Description The data is copied in column-major order.
void SetCharData(mxChar* buffer, mwSize len) Purpose C++ Syntax Arguments Copy data from supplied mxChar buffer into array #include "mclcppclass.h" mxChar data[6] = {'H', 'e' , 'l' , 'l' , 'o' , '\0'}; mxChar data_copy[6] ; mwArray a(1, 6, mxCHAR_CLASS); a.SetData(data, 6); a.GetData(data_copy, 6); buffer Buffer containing data to copy len Maximum length of buffer. A maximum of len elements will be copied. Return Value None Description The data is copied in column-major order.
mwArray operator()(mwIndex i1, mwIndex i2, mwIndex i3, ..., ) Purpose C++ Syntax Arguments Return single element at specified 1-based index #include "mclcppclass.h" double data[4] = {1.0, 2.0, 3.0, 4.0}; double x; mwArray a(2, 2, mxDOUBLE_CLASS); a.SetData(data, 4); x = a(1,1); // x = 1.0 x = a(1,2); // x = 3.0 x = a(2,2); // x = 4.0 i1, i2, i3, ..., Comma-separated list of input indices C-84 Return Value An mwArray containing the value at the specified index.
mwArray operator()(const char* name, mwIndex i1, mwIndex i2, mwIndex i3, ..., ) Purpose C++ Syntax Arguments Return single element at specified field name and 1-based index in struct array #include "mclcppclass.h" const char* fields[] = {"a", "b", "c"}; int index[2] = {1, 1}; mwArray a(1, 1, 3, fields); mwArray b = a("a", 1, 1); mwArray b = a("b", 1, 1); // b=a.a(1,1) // b=a.b(1,1) name NULL-terminated string containing the field name to get i1, i2, i3, ...
mwArray& operator=(const & x) Purpose Assign single scalar value to array C++ Syntax Arguments #include "mclcppclass.h" mwArray a(2, 2, mxDOUBLE_CLASS); a(1,1) = 1.0; // assigns a(1,2) = 2.0; // assigns a(2,1) = 3.0; // assigns a(2,2) = 4.0; // assigns 1.0 2.0 3.0 4.0 to to to to element element element element x Value to assign C-86 Return Value A reference to the invoking mwArray. Description Use this operator to set a single scalar value.
operator () const Purpose C++ Syntax Fetch single scalar value from array #include "mclcppclass.h" double data[4] = {1.0, 2.0, 3.0, 4.0}; double x; mwArray a(2, 2, mxDOUBLE_CLASS); a.SetData(data, 4); x = (double)a(1,1); x = (double)a(1,2); x = (double)a(2,1); x = (double)a(2,2); // // // // x x x x = = = = 1.0 3.0 2.0 4.0 Arguments None Return Value A single scalar value from the array. Description Use this operator to fetch a single scalar value.
static mwArray Deserialize(const mwArray& arr) Purpose C++ Syntax Arguments Deserialize array that was serialized with mwArray::Serialize #include "mclcppclass.h" double rdata[4] = {1.0, 2.0, 3.0, 4.0}; mwArray a(1,4,mxDOUBLE_CLASS); a.SetData(rdata, 4); mwArray b = a.Serialize(); a = mwArray::Deserialize(b);// a should contain same // data as original arr mwArray that has been obtained by calling mwArray::Serialize C-88 Return Value A new mwArray containing the deserialized array.
static double GetNaN() Purpose C++ Syntax Get value of NaN (Not-a-Number) #include "mclcppclass.h" double x = mwArray::GetNaN(); Arguments None Return Value The value of NaN (Not-a-Number) on your system. Description Call mwArray::GetNaN to return the value of NaN for your system. NaN is the IEEE arithmetic representation for Not-a-Number. Certain mathematical operations return NaN as a result, for example: • 0.0/0.0 • Inf-Inf The value of NaN is built in to the system; you cannot modify it.
static double GetEps() Purpose C++ Syntax C-90 Get value of eps #include "mclcppclass.h" double x = mwArray::GetEps(); Arguments None Return Value The value of the MATLAB eps variable. Description Call mwArray::GetEps to return the value of the MATLAB eps variable. This variable is the distance from 1.0 to the next largest floating-point number. Consequently, it is a measure of floating-point accuracy. The MATLAB pinv and rank functions use eps as a default tolerance.
static double GetInf() Purpose C++ Syntax Get value of Inf (infinity) #include "mclcppclass.h" double x = mwArray::GetInf(); Arguments None Return Value The value of Inf (infinity) on your system. Description Call mwArray::GetInf to return the value of the MATLAB internal Inf variable. Inf is a permanent variable representing IEEE arithmetic positive infinity. The value of Inf is built into the system; you cannot modify it. Operations that return Inf include • Division by 0.
static bool IsFinite(double x) Purpose C++ Syntax C-92 Test if value is finite and return true if value is finite #include "mclcppclass.h" bool x = mwArray::IsFinite(1.0); // Returns true Arguments Value to test for finiteness Return Value Result of test. Description Call mwArray::IsFinite to determine whether or not a value is finite. A number is finite if it is greater than -Inf and less than Inf.
static bool IsInf(double x) Purpose C++ Syntax Test if value is infinite and return true if value is infinite #include "mclcppclass.h" bool x = mwArray::IsInf(1.0); // Returns false Arguments Value to test for infinity Return Value Result of test. Description Call mwArray::IsInf to determine whether or not a value is equal to infinity or minus infinity. MATLAB stores the value of infinity in a permanent variable named Inf, which represents IEEE arithmetic positive infinity.
static bool IsNaN(double x) Purpose C++ Syntax Test if value is NaN (Not-a-Number) and return true if value is NaN #include "mclcppclass.h" bool x = mwArray::IsNaN(1.0); // Returns false Arguments Value to test for NaN Return Value Result of test. Description Call mwArray::IsNaN to determine whether or not the value is NaN. NaN is the IEEE arithmetic representation for Not-a-Number. NaN is obtained as a result of mathematically undefined operations such as • 0.0/0.
Index A Index addpath command 4-18 Addressing Extended 2 GB Limit 7-3 Advanced Encryption Standard (AES) cryptosystem 3-2 ANSI compiler installing 2-5 application POSIX main 5-10 application coding with M-files and C/C++ files 6-13 M-files only 6-11 axes objects 12-5 B bcc55compp.bat file 2-9 bcc55freecompp.bat file 2-9 bcc56compp.
Index D debugging 5-24 -G option flag 11-21 dependency analysis 3-4 depfun 4-17 deployed applications licensing 9-11 troubleshooting 8-8 using relative path 5-23 deploying applications that call Java native libraries 5-25 deploying components from a network drive 4-24 deploying GUIs with ActiveX controls 5-24 deploying recompiled applications 4-23 deploying to different platforms 4-15 deployment 4-2 deployprint function 11-8 deploytool quick start 1-7 deploytool function 11-10 directory user profile 2-12 D
Index G -G option flag 11-21 GUI compiling with ActiveX controls 5-24 deploying as shared library 5-28 displaying 5-28 H Handle Graphics 12-5 I input/output files 3-6 C shared library 3-7 C++ shared library 3-9 standalone 3-6 interfacing M-code to C/C++ code 5-13 internal error B-2 isdeployed 8-4 J Java native libraries deploying applications that call 5-25 L lcccompp.bat file 2-9 libraries overview 1-10 library shared C/C++ 7-2 wrapper 5-12 license problem 2-4 8-4 9-12 license.
Index options 5-2 summarized A-4 syntax 10-2 11-17 system requirements UNIX 2-2 troubleshooting 8-4 warning messages B-2 MATLAB Compiler license 9-11 MATLAB Component Runtime (MCR) 3-2 matrixdriver on Mac OS X 7-36 msvc80compp.bat file 2-9 msvc80freecompp.bat file 2-9 MX_COMPAT_32_OFF 7-3 mxArrays Passing to shared libraries 7-38 N network drive deploying from 4-24 -nocache 11-28 mbuild 2-7 options 11-12 troubleshooting 8-2 mcc 11-17 Compiler 2.
Index pathnames handling full 5-7 PLP (personal license password) 2-4 porting code 4-15 POSIX main application 5-10 POSIX main wrapper 5-10 pragma %#external 10-2 11-2 feval 10-2 11-3 %#function 10-2 11-3 prerequisites 1-5 primitive types C-2 problem with license 2-4 Q quick start compiling a shared library 1-10 quotation marks with mcc options 5-9 quotes with mcc options 5-9 R relative path running deployed applications 5-23 resolving conflicting options 5-3 rmpath 4-18 S script file 5-19 including in
Index options file 2-9 locating 2-12 Windows compiler limitations 2-11 wrapper code generation 3-5 wrapper file 1-3 wrapper function 5-10 wrappers Index-6 C shared library 5-11 C++ library 5-12 main 5-10 Z -z option flag 11-27