The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
government’s needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Docu mentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Builder™ NE User’s Guide
Revision History
March 2006Online onlyNew for Version 2.0 (Release 2006a)
September 2006 Online onlyRevised for Version 2.1 (Release 2006b)
March 2007Online onlyRevised for Version 2.2 (Release 2007a)
September 2007 Online onlyRevised for Version 2.2.1 (Release 2007b)
March 2008Online onlyRevised for Version 2.2.2 (Release 2008a)
October 2008Online onlyRevised for Version 3.0 (Release 2008b)
March 2009Online onlyRevised for Version 3.0.1 (Release 2009a)
September 2009 Online onlyRevised for Version 3.0.2 (Release 2009b)
March 2010Online onlyRevised for Version 3.1 (Release 2010a)
MATLAB
Common Language Specification (CLS) Compliancy
Data Conversion, Indexing, and Array Formatting
Error Handling
Remotable Components
COM Components
Supported Microsoft .NET Framework Versions
Limitations of Support
Before You Use MATLAB
Your Role in the .NET Application Deployment Process
What You Need to Know
Install Required Products
Deploying a Component Using the Magic Square
Example
About This Example
Magic Square Example: MATLAB Programmer Tasks
Using the Command Line to Create .NET Components
Magic Square Example: .NET Programmer Tasks
Next Steps
®
Compiler Extension ......................1-2
.....1-2
......1-3
...................................1-3
............................1-3
.................................1-3
........1-4
.............................1-4
®
Builder NE ...............1-5
..1-5
............................1-7
...........................1-8
........................................1-9
...............................1-9
...1-10
...1-17
.......1-23
........................................1-34
Writing Deployable MATLAB Code
2
The MATLAB Application Deployment Products.....2-2
v
Building Your Application w ith the Application
Deployment Products and the D e ploy ment Tool
What Is the Difference Between the Deployment Tool and
the mcc Command Line?
How Does MATLAB
Application?
What You Should Know About the Dependency Analysis
Function (depfun)
Compiling MEX-Files, DLLs, or Shared Lib rari es
The Role of the Component Technology File (CTF
Archive)
.......................................2-7
®
Compiler Software Build My
....................................2-4
...............................2-5
.........................2-4
....2-4
.......2-6
Guidelines for Writing Deployable MATLAB Code
Compiled Applications Do No t Process MATLAB Files at
Runtime
Do Not Rely on Changing Directory or Path to Control the
Execution of MATLAB Files
Use ismcc and isdeployed Functions To Execute
Deployment-Specific Code Paths
Gradually Refactor Applications That Depend o n
Noncompilable Functions
Do Not Create or Use Nonconstant Static State
Variables
Working with MATLAB Data Files Using Load and
Save
Using Load/Save Functions to Process MATLAB Data for
Deployed Applications
.......................................2-10
....................... 2-11
................... 2-11
......................... 2-12
......................................2-12
............................................2-14
........................... 2-14
Using Components Created by the MATLAB
Builder NE Product
3
....2-10
®
viContents
Installing the Components on the Development
Machine
Specifying Component Assembly and Namespace
Creating an Instance of a Class
........................................3-2
.....................3-4
.....3-3
Using Dispose to E x plicitly Free Resources ..........3-5
ImprovingDataAccessUsingtheMCRUserData
Interface and MATLAB
Code Snippets
Example
Dynamically Specifying Run-Time Options to the
MCR
What Run-Time Options Can You Specify?
Getting MCR Option Values Using MWMCR
Accessing Real or Imaginary Components Within
Complex Arrays
Extracting Real or Imaginary Components
Returning Values with Component Indexing
Assigning Values with Component Indexing
Converting MATLAB Arrays to .NET Arrays Using
Blocking Execution of a Console Application that
Creates Figures
WaitForFiguresToDie Method
Code Fragment: Using WaitForFiguresToDie to Block
...........................................3-11
Component Indexing
Execution
....................................3-6
.........................................3-7
......................................3-18
®
Builder NE ...............3-6
.............3-11
...........3-11
.................................3-14
.............3-14
...........3-14
............3-15
............................. 3-15
.................................3-17
....................... 3-17
Using MATLAB API Functions in a C# Program
Overview
Example: Using functions engOpen and engEvalString
from the MATLAB Engine API in a C# Program
Handling Errors
Overriding Default CTF Archive Embedding for
Components Using the MCR Component Cache
Using Enhanced XML Documentation Files
........................................3-20
...................................3-22
..........3-26
......3-20
......3-20
....3-24
vii
Sample Applications (C#)
4
Simple Plot Example ...............................4-2
Purpose
Procedure
.........................................4-2
........................................4-2
Passing Variable Arguments
Spectral Analysis Example
Purpose
Procedure
Matrix Math Example
Purpose
Procedure
MATLAB F unctions to Be Encapsulated
Understanding the MatrixMath Program
Phonebook Example
Purpose
Procedure
.........................................4-13
........................................4-15
.........................................4-20
........................................4-21
.........................................4-28
........................................4-28
Sample Applications (Microsoft®Visual Basic
5
........................4-7
......................... 4-13
.............................. 4-20
...............4-26
..............4-27
............................... 4-28
.NET)
viiiContents
Magic Square Example (Visual Basic)...............5-3
Create Plot Example (Visual Basic)
Variable Arguments Example (Visual Basic)
Spectral Analysis Example (Visual Basic)
..................5-7
.........5-11
............5-15
Matrix Math Example (Visual Basic) .................5-20
Phonebook Example (Visual Basic)
makephone Function
Procedure
........................................5-25
............................... 5-25
.................. 5-25
Deploying a MATLAB Figure Over the Web
Using WebFigures
6
About the WebFigures Feature ......................6-2
Supported Renderers for WebFigures
Before You Use WebFigures
Your Role in the .NET WebFigure Deployment Process
What You Need to Know to Implement WebFigures
Required Products
Assumptions About the Examples
Quick Start: Implementing a WebFigure
Overview
Procedure
........................................6-7
........................................6-7
.................................6-5
........................6-3
.................6-2
....................6-6
.............6-7
...6-3
.....6-5
Advanced Configuration of a WebFigure
Overview
Manually Installing WebFigureService
Retrieving Multiple WebFigu r es From a Component
Attaching a WebFigu re
Setting Up WebFigureControl for Remote Invocation
Getting an Embeddable String That References a
WebFigure Attached to a WebFigureService
Improving Processing Times for JavaScript Using
Minification
Using Global Application Class (Global.asax) to Create
Your Role in Working with Figures and Images ......7-2
Creating an d Modifying a MATLAB Figure
Preparing a MATLAB F igure for Export
Changing the Figure (Optional)
Exporting the Figure
Cleaning Up the Figure Window
Example: Modifying and Exporting Figure Data
Working with MATLAB Figure and Image Data
For More Comprehensive Examples
Working with Figures
Working with Images
What Are Remotable Co mponents?
Benefits of Using .NET Remoting
Your Role in Building Distributed Applications
Selecting th e Best Method of Accessing Your
Component: MWArray API or Native .NET API
Using Native .NET Structure and Cell Arrays
...................8-2
....................8-2
......8-4
..........8-6
.....8-5
Creating a Remotable .NET Component.............8-7
Building a Remotable Component Using the Deployment
Tool
..........................................8-7
Building a Remotable Component Using the mcc
Command
Files Generated by the Compilation Process
.....................................8-10
............8-10
Enabling Access to a Remotable .NET Component
UsingtheMWArrayAPI
Using the Native .NET API: The Magic Square Example
Using the Native .NET API: The Cell and Struct
Example
.......................................8-26
........................... 8-12
Troubleshooting
9
Troubleshooting the Build Process.................9-2
Viewing the Latest Build Log
Generating Verbose Output
Failure to Find a Required File
Diagnostic Messages
Enhanced E rror Diagnostics Using mstack Trace
...............................9-4
........................9-2
.........................9-2
.....................9-3
.......9-6
....8-12
..8-19
10
Reference Information
Requirements for the MATLAB®Builder NE Product ..10-2
System Require ments
Compiler Requirements
Path M odifications Required for Accessibility
Limitations and Restrictions
Data Conversion Rules
............................. 10-2
............................ 10-2
...........10-3
........................ 10-3
............................. 10-4
xi
Managed Types to M ATLA B Arrays .................. 10-4
MATLAB Arrays to Managed Types
Character and String Conversion
Unsupported MATLAB Array Types
.................. 10-5
.................... 10-5
.................. 10-6
11
12
Overview of Data Conversion Classes
Overview
Returning Data from MATLAB to Managed Code
Example of MWNumericArray in a .NET Application
Interfaces Generated by the MATLAB
Product
MWArray Class Specification
........................................10-7
.......................................10-8
....................... 10-14
...............10-7
.......10-8
®
Builder NE
....10-8
Function Reference
Creating and Installing COM Components
Building a Deployable COM Component .............12-2
xiiContents
Packaging a Deployable COM Component
About Embedded CTF Archives
Using the Command-Line Interface
Installing COM Components on a Target Computer
..................... 12-5
................. 12-6
...........12-4
...12-9
13
Programming with COM Components Created
by the MATLAB
General Techniques ................................13-2
®
Builder NE Product
Registering and Referencing the Utility Library
Creating an Instance of a Class in Microsoft
Basic
Advantages and Disadvantages
CreateObject Function
Microsoft
Advantages of Each Technique
Declaring a Reusable Class Instance
Calling the Methods of a Class Instance
Standard Mapping Technique
Variant
Examples of Passing Input and Output Parameters
Calling a COM Object in a Visual C++ Program
Using the MATLAB
Using the Component in a Visual C++ Program
Using a COM Component in a .NET Application
Overview
C# Implementation
Microsoft
...........................................13-5
...................... 13-5
............................. 13-5
®
Visual Basic New Operator ................13-6
...................... 13-7
.................. 13-7
....................... 13-8
..........................................13-9
®
Builder NE Product to Create the
Object
......................................... 13-11
........................................ 13-14
................................ 13-14
®
Visual Basic Implementation ............... 13-17
®
Visual
..............13-8
......... 13-12
......13-4
.....13-9
....... 13-11
...... 13-14
Adding Events to COM Objects
MATLAB Language Pragma
Using a Callback with a Microsoft
Passing Arguments
Overview
Creating and Using a varargin Array in Microsoft
Basic Programs
........................................ 13-26
................................ 13-26
................................. 13-26
...................... 13-21
........................ 13-21
®
Visual Basic Event ... 13-22
®
Visual
xiii
Creating and Using varargout in Microsoft®Visual Basic
Programs
Passing an Empty varargin From Microsoft
Code
Using Flags to Control Array Formatting and Data
Conversion
Overview
Array Formatting Flags
Using Array Formatting Flags
Using Data Conversion Flags
Special Flags for Some Microsoft
...................................... 13-27
®
Visual Basic
.......................................... 13-28
..................................... 13-29
........................................ 13-29
............................ 13-30
....................... 13-30
........................ 13-33
®
Visual Basic Types .... 13-35
14
Using MATLAB Global Variables in Microsoft
Basic
Blocking Execution of a Console Application that
Creates Figures
MCRWaitForFigures
Using MCR WaitForFig ures to Block Execution
Obtaining Registry Information
Handling Errors During a Method Call
........................................... 13-36
................................. 13-39
............................... 13-39
..................... 13-42
®
Visual
......... 13-40
.............. 13-44
Using COM Components in Microsoft®Visual
Basic Applications
Magic Square Example ............................. 14-2
Example Overview
Creating the MATLAB File
Using the Deployment Tool to Create and Build the
Project
Creating the Microsoft
Creating the User Interface
Creating the Executable in Microsoft
Testing the Application
........................................14-3
................................14-2
......................... 14-2
®
Visual Basic Project ...........14-4
......................... 14-4
®
Visual Basic ......14-7
............................. 14-7
xivContents
Packaging the Component .......................... 14-8
Creating an Excel Add-In: Spectral Analysis
Example
Example Overview
Building th e Component
Integrating the Component with VBA
Creating the Microsoft
Adding the Spectral A nalysis Menu Item to Microsoft
Magic Square Example for .NET ....................A-2
Using Load and Save
UsingtheMCRDataInterface
Passing MCR Option Values from a C# Application
Using WaitForFiguresToDie to Block Execution
...............................A-2
......................A-2
...A-2
......A-2
Using functions engOpen and engEvalString from the
MATLAB Engine API in a C# Program
Sample Applications (C#)
Sample Applications (Visual Basic .NET)
Quick Start to Implementing a WebFigure
Working with Functions that Return a Single
WebFigure as the Function’s Only Output
...........................A-3
.............A-2
............A-3
...........A-3
.........A-3
xvii
Working With Functions That Return Multiple
WebFigures In an Array as the Output
............A-4
Attaching a WebFigure
Referencing a WebFigure Attached to the Local
Server
Referencing a WebFigure Attached to a Remote
Server
Using Global Application Class (Global.asax) to Create
WebFigures at Server Start-Up
Creating an d Modifying a MATLAB Figure
Working with MATLAB Figures
Working with Images
Building a Remotable Component Using the
Deployment Tool
Building a Remotable Component Using the mcc
Command
..........................................A-4
..........................................A-4
.......................................A-5
.............................A-4
...................A-4
...........A-4
.....................A-5
..............................A-5
................................A-5
xviiiContents
Using Native .NET Structure and Cell Arrays
COM Components
Utility Library Classes for COM Components
.................................A-5
........A-5
........A-6
Glossary
Index
xix
xxContents
Getting Started
• “Product Overview” on page 1-2
®
• “Before You Use MATLAB
• “Deploying a Component Using the Magic Square Example” on page 1-9
• “Next Steps” on page 1-34
Builder NE” on page 1-5
1
1 Getting Started
Product Overview
MATLAB Compiler Extension
MATLAB®Builder™ NE is an extension to MATLAB®Compiler™. The
builder converts MATLAB
MATLAB code written by the MATLAB programmer. All MATLAB code to
be compiled must be in the form of a function. Each MATLAB Builder NE
component contains one or more classes, each providing an interface to the
MATLAB functions in the MATLAB code.
In this section...
“MATLAB®Compiler Extension” on page 1-2
“Common Language Specification (CLS) Compliancy” on page 1-2
“Data Conversion, Indexing, and Array Formatting” on page 1-3
“Error Handling” on page 1-3
“Remotable Components” on page 1-3
“COM Components” on page 1-3
“Supported Microsoft .NET Framework Versions” on page 1-4
“Limitations of Support” on page 1-4
®
functions to .NET methods that encapsulate
1-2
When you package and distribute the application to your users, you include
supporting files genera ted by the builder as well as the MATLAB Compiler
Runtime (MCR). For more information about the MCR, see “What Is
The MATLAB Compiler Runtime (MCR)?” in the MATL AB Compiler
documentation.
For more information about how this product works with MATLAB Compiler,
see “Writing Deplo yable MATLAB Code”.
Common Language Specification (CLS) Compliancy
CLS is an acronym for Common Language Specification.CLSisasubsetof
language features supported by the .NET common language runtime (CLR).
MATLAB Builder NE classes are CLS compliant—they are guaranteed to
integrate seamlessly with all .NET programming languages. CLS-compliant
Product Overview
languages are guaranteed to interoperate w ith other CLS-compliant
components and tools.
UsethebuildertopackageMATLABfunctionssothat.NETprogrammers
can access them from any CLS-compliant language.
Data Conversion, Indexing, and Array Formatting
The builder provides robust data conversion, indexing, and array formatting
capabilities. For example, to support MATLAB data types, the MATLAB
Builder NE product provides the
MATLAB Builder NE
your managed application to convert native arrays to MATLAB arrays and
vice versa.
MWArray assembly. You reference this assembly in
MWArray data conversion classes in the
Error Handling
The builder also provides custom error handling so that errors originating
from MATLAB functions are reported as standard managed exceptions. The
error description contains specific references to the MATLAB code, thus
simplifying the debugging process.
Remotable Components
Remotable .NET components allow you to access MATLAB functionality
remotely, as part of a distributed system consisting of multiple applications,
domains, browsers, or machines. They also enable your component to be
deployed in other capacities, such as a Windows
For detailed instructions about creating remotable .NET components, see
Chapter 8, “Sharing Components Across Distributed Applications Using
.NET Remoting”.
®
service, for example.
COM Components
You can also use the builder to create COM components. COM stands for
Component Object Model, which is a software architecture developed by
Microsoft
interfaces that allow applications and other components to access the features
of the objects. COM objects are accessible through Microsoft
®
to build com ponent-based applications. COM objects expose
®
Visual Basic®,
1-3
1 Getting Started
C++, or any lang uage that supports CO M objects. For more information
about creating and accessing COM components, see Chapter 12, “Creating
and Installing COM Components” and Chapter 13, “Programming with COM
Components Created by the MATLAB
®
Builder NE Product”.
Supported Microsoft .NET Framework Versions
As of this rele ase, version s 2.0, 3.0, and 3.5 of the Microsoft .NET Framework
are supported.
All of these supported releases are based on the CLS 2.0 specification.
Specifying
of the Framework installed on your system.
0.0 as the .NET Framework indicates to supply the latest version
Limitations of Support
MATLAB Builder NE provides a wide variety of support for various
CLS-compliant types and objects. However, MATLAB (MCOS) objects are not
supported as inputs or outputs for compiled or deployed functions.
1-4
Before You Use MATLAB Builder NE
In this section...
“Your Role in the .NET Application Deployment Process” on page 1-5
“What You Need to Know” on page 1-7
“Install Required Products” on page 1-8
Your Role in the .NET Application Deployment Process
Depending on the size of your organization, you may play one or more roles
in the process of successfully deploying a .NET application. For example,
your role may be to:
• Analyze user requirements and satisfy them by writing a program in
MATLAB code.
• Implement the infrastructure needed to successfully deploy a .NET
application to the Web.
Before You Use MATLAB®Builder™ NE
• Create a remotable component that can be shared across distributed
systems.
• Perform tasks associated with numerous roles (particularly in a smaller
organization).
The table Application Deployment Roles, Goals, and Tasks on page 1-6
describes some of the different roles, or jobs, that MATLAB Builder NE users
typically perform and which tasks they would most likely perform when
running the examples in this documentation.
1-5
1 Getting Started
Application Deployment Roles, Goals, and Tasks
RoleGoalsTask To A chieve Goal
MATLAB prog rammer
• Understand the
end-user business
requirements and
the mathematical
models needed to
support them.
• Build an executable
component with
MATLAB tools
(usually with
support from a .N ET
programmer).
• Package the
component for
distribution to end
users.
• Pass the packaged
component to the
.NET programmer
for rollout and
further integration
into the end-user
environment.
See “Magic Square
Example: MATLAB
Programmer Tasks” on
page 1-10.
1-6
.NET programmer
• Write.NETcodeto
execute the .NET
assembly built
by the MATLAB
programmer.
• Roll out the packaged
component and
integrate it into
the end user’s
environment.
See “Magic Square
Example: .NET
Programmer Tasks”
on page 1-23.
Before You Use MATLAB®Builder™ NE
Application Deploym ent Roles, Goals, and Tasks (Continued)
RoleGoalsTask To A chieve Goal
• Use the component
in enterprise .NET
applications, adding
and modifying code
as needed.
• Address data
conversion issues
that may be
encountered,
according to the end
user’s specifications.
• Ensure the final
.NET application
executes reliably
in the end user’s
environment.
External userExecute the
solution created by
MATLAB and .NET
programmers.
Run the deployed
application (outside the
scope of this document).
What You Need to Know
To use the MATLAB Builder NE product, specific requirements exist for each
user role.
1-7
1 Getting Started
Role
MATLAB programmer• A basic knowledge of MATLAB,
Requirements
and how to work with:
- MATLAB data types
- MATLAB structures
.NET programmer• Exposure to:
- A CLS-compliant programming
language
- .NET Framework
• Knowledge of object-oriented
programming concepts
Install Required Products
Install the following products to run the example described in this chapter:
• MATLAB
• MATLAB Compiler
• MATLAB Builder NE
1-8
• AsupportedCorC++compiler
For more information about product installation and requirements, see
“Installation and Configuration”.
Deploying a Component Using the Magic Square Example
Deploying a Component Using the Magic Square Example
In this section...
“About This Example” on page 1-9
“Magic Square Example: MATLAB Programmer Tasks” on page 1-10
“Using the Command Line to Create .NET Components” on page 1-17
“Magic S q u a re Example: .NET Programmer Tasks” on page 1-23
About This Example
This example shows you how to transform a simple MATLAB code function
into a deployable MATLAB Builder NE component.
The Magic Square example shows you how to create a .NET component
named
other files needed to deploy your application.
MagicSquareComp, which contains the magicSquareClass class and
The
magicSquareClass wraps a M ATLA B function, makesquare,which
computes a magic square. A magic square is a matrix containing any number
of rows. These rows, added horizontally, vertically, or diagonally, equate to
the same value. MATLAB contains a function,
create magic squares of any dimension.
Note TheexampleshereusetheWindowsdeploytool GUI, a graphical
front-end interface to MATLAB Compiler software. For information about
how to perform these tasks using the command-line interface to MATLAB
Compiler software, see the
Note Ifyouwishtocreatearemotable component, and for information about
what this entails, see Chapter 8, “Sharing Components Across Distributed
Applications Using .NET Remoting”.
mcc reference page.
magic,thatyoucanuseto
1-9
1 Getting Started
Magic Square Exa
The MATLAB progr
Key Tasks for th
Task
1. Prepare to run the example by
copying the MATLAB example files
into a work folder.
2.TesttheMATLABcodetoensure
it is suitable for dep l oyment.
3. Create a .NET component
(encapsulating your MATLAB code
in a .NET class) by running the
Build function in
4. Prepa
Tool by d
files to
compon
5. Copy
re to run the Packaging
etermining what additional
include with the deployed
ent.
the output.
e MATLAB Programmer
deploytool.
mple: MATLAB Programmer Tasks
ammer usually performs the following tasks.
Reference
“Copying the Example Files” on page
1-10
“Testing the MATLAB File You
Want to Deploy” on page 1-11
“Building Your Component” on page
1-12
“Packaging Your Component
(Optional)” on page 1-16
Deploying a Component Using the Magic Square Example
Tip matlabroot is the MATLAB root folder (where MATLAB is installed).
To find the value of this variable on your system, type
matlabroot at a
MATLAB command prompt.
2 Copy the MagicSquareExample folder to a work area, for example,
D:\dotnetbuilder_examples. Avoid using spaces in your folder
names, if possible. The example files should now reside in
D:\dotnetbuilder_examples\MagicSquareExample.
3 Using a command prompt, navigate to
D:\dotnetbuilder_examples\MagicSquareExample by switching to the D:
drive and entering cd \dotnetbuilder_examples\MagicSquareExample.
Testing the M ATLAB File You Want to Deploy
In this example, you test a precreated MATLAB file (magicsquare .m)
containing the predefined MATLAB function
baselinetocomparetotheresultsofthe function when it is finally wrappered
as a deployable .NET component.
function y = makesquare(x )
%MAKESQUARE Magic square o f size x.
%Y = MAKESQUARE(X) returns a magic square of size x.
%This file is used as an example for the MATLAB
%Builder NE product.
%Copyright 2001-2009 The MathWorks, Inc.
y = magic(x);
2 At the MATLAB command prompt, enter makesq uare(5) and view the
results. The output should appear as follows:
17 2418 15
2357 14 16
1-11
1 Getting Started
46 13 20 22
10 12 19 213
11 18 2529
About MATLAB Function Signatures. MATLAB supports multiple
signatures for function calls.
The generic MATLAB function has the following structure:
function [Out1,Out2,...,varargout]=foo(In1,In2,...,vararg in)
To the left of the equal sign, the function specifies a set of explicit and optional
return arguments.
To the right of the equal sign, the function lists explicit input arguments
followed by one or more optional arguments.
All arguments represent a specific MATLAB type.
1-12
When the MATLAB Builder NE product processes your MATLAB code, it
creates several overloaded methods that implement the MATLAB functions.
Each of these overloaded methods corresponds to a call to the generic
MATLAB function with a specific number of input arguments. In addition to
these methods, the builder creates another method that defines the return
values of the MATLA B function as an input argument. This method simulates
the
feval external API interface in MATLAB.
Building Your Component
You create a .NET component by using the Deployment Tool GUI to build
a .NET class that wraps around the sample MATLAB code discussed in
“Testing the MATLAB File You Want to Deploy” on page 1-11.
Use the following information when creating your component as you work
through this example:
Project Name
Class Name
File to compile
magicSquareComp
magicSquareClass
makesquare.m
Deploying a Component Using the Magic Square Example
1 Start MATLAB.
2 Type deploytool at the comman d prompt and press Enter. Th e
deploytool GUI opens.
3 Create a deployment project using the Deployment Project dialog:
a TypethenameofyourprojectintheName field.
b Enter the location of the project in the Location field. Alternately,
navigate to the location.
c Sele ct the target for the deployment project from the Target drop-down
menu.
d Click OK.
Creating a .NET Project
4 On th
e Build tab:
• If yo
• If y
u are building a COM application, click Add files
ou are building a .NET application, click Add class. Type the name
he class in the Class Name field, designated by the letter “c”:
of t
1-13
1 Getting Started
For this class, add files you want to compile by clicking Add files.To
add another class, click Add class.
Note You may optionally add supporting files. For examples of these
files, see the
deploytool Help. To add these files, in the Shared Resources
and Helper Files area:
a Click Add files/directories
b Click Open to select the file or files.
5 When you complete your changes, click the Build button ().
How the .NET Builder Creates a Component. To create a component, the
builder does the following:
1 Generates C# code to implement your component
1-14
The first step of the build process generates two C# files: a component data
file and a component wrapper. The component data file contains static
information for the component. The wrapper contains the implementation
code for the .NET component and provides a .NET application programming
interface (API) for the MATLAB f unctions you add to the project at design
time.
2 Compiles the C# code and generates /distrib and /src subfolders
Thesecondstepofthebuildprocesscompiles the two C# files produced in
step 1, creating a managed assembly for the component.
The MATLAB Builder NE product creates two subfolders under the project
folder:
project-folder/src and project-folder/distrib.These
subfolders contain the following files.
Files in the Project Subfolders
Deploying a Component Using the Magic Square Example
Subfolder
src
distrib
Files
ComponentName
_mcc_component_data.cs
ClassName1.cs ...
ClassNameN.cs
ComponentName.dll
ComponentName.pdb
ComponentName.xml
ComponentNameNative.dll
MWArray.xml
component_name.xml
component_name_overview.html
readme.txt
Description
C# component data
file
C# wrapper class file
.NET component
assembly
.NET component
debug file (Debug
builds only)
.NET component
XML d ocumentation
file
Native .NET DLL
(See “Remotable
Components”
on page 1-3 for
information).
Documentation
template files.
See “Using
Enhanced XML
Documentation
Files” on page 3-26.
Readme file for
users
Note When you build your project, you can specify the compilation of a
private or shared assembly. A private assembly is copied to an application
subfolder and is owned exclusively by the application. A shared assembly
usually resides in the Global Assembly Cache, and can be directly
referenced by multiple applications.
1-15
1 Getting Started
For information about how the builder works in conjunction w ith MATLAB
Compiler, see “How D oe s MATLAB
®
Compiler Software Build My
Application?” on page 2-4 in the MATLAB Compiler User’s Guide.
Packaging Your Component (Optional)
Bundling the .NET component with additional files you can distribute to
users is called packaging. You perform this step using the packaging function
of
deploytool. Alternately, copy the contents of the distrib folder and the
MCR Installer to a local folder of your choice. If you are creating a shared
component and want to include additional code with the component, you m ust
perform this step.
1 On the Package tab, add the MATLAB Compiler Runtime (the MCR) by
clicking Add MCR.
2 Next, add others files useful for end users. The readme.txt file contains
important information about others files useful for end users. To package
additional files or folders, click Add file/directories, select the file or
folder you want to package, and click Open.
3 In the Deployment Tool, click the Packaging button ().
4 On Windo
other t
distri
ws, the package is a self-extracting executable. O n platforms
han Windows, it is a
b
folder contains the files you specified.
.zip file. Verify that the contents of the
1-16
Note W
VCRED
of Mic
appl
What
lowing files into a single self-extracting executable,
fol
•
com
• co
hen the self-extracting executable is uncompressed on a system,
SIT_X86
is installed. VCREDSIT_X86 installs run-time components
rosoft Visual C++ libraries necessary for running Visual C++
ications.
Happens in the Packaging Process?. Thepackageprocesszipsthe
ponentName.dll
mponentNameNative.dll
componentName.exe:
Deploying a Component Using the Magic Square Example
Note See “Remotable Components” on page 1-3 and Chapter 8, “Sharing
Components Across Distributed Applications Using .NET Remoting” for
more details.
• componentName.xml
• componentName.pdb (if the Debug option is selected)
MCRInstaller.exe (if the Include MCR option is selected)
•
_install.bat (script run by the self-extracting executable)
•
How the MCR Is Shared Among Classes. The builder creates a single
MCR instance for each MATLAB Builder NE class in an application. This
MCR instance is reused and shared among all subsequent class instances
within the component, resulting in more efficie nt memory usage and
eliminating the MCR startup cost in each subsequent class instantiation. All
class instances share a single MATLAB workspace and share global variables
in the MATLAB files used to build the component.
The following example creates a .NET component called
mycomponent
containing a single .NET class named myclass with methods foo and bar.
If and when multiple instances of
only one MCR is initialized, and it is shared by all instances of
Copy the package that you created from the distrib folder to the local folder
of your choice or send them directly to the .NET programmer.
Using the Command Line to Create .NET Components
Instead of using the Deployment Tool to create .NET components, you can
use the
mcc command.
1-17
1 Getting Started
The following sections describe the subset of mcc command options that you
need to create .NET components. The sections provide detailed
mcc syntax
with examples.
To learn more about the
Compiler documentation.
Command-Line Syntax Description
The following command defines the complete mcc command syntax with all
required and optional arguments used to create a .NET component. Brackets
indicate optional parts of the syntax.
Note For complete information about the mcc command, including the -W
option, see mcc in the function reference section of this user’s guide.
Using the Command Line to Start the Deployment Tool GUI
Desired ResultCommand
Starts Deployment
Tool GUI with the
New/Open dialog
active
Starts Deployment
Tool GUI and loads
project_name
Starts Deployment
Tool command line
interface and build s
project_name after
initializing
deploytool (default)
or
deploytool -n
deploytool project_name.prj
deploytool -build project_name.prj
mcc command and all of its options, see the MATLAB
[class{class_name:file1
[-d output_dir_path] -T link:lib
1-18
Desired ResultCommand
Starts Deployment
deploytool -package project_name.prj
Tool command line
interface and packages
project_name after
initializing
Displays M ATLAB Help
for the
deploytool
deploytool -?
command
Using the .NET Bundle Files to Simplify the Command
To simplify the command line used to create .N ET components, you can
use the .NET Builder bundle file, named
components easier. When using this bundle file, you must still pass in the five
parts (including
donothavetospecifythe
Deploying a Component Using the Magic Square Example
dotnet, to make creating .NET
local|remote)ofthe-W argument text string, however, you
-T option.
The following example creates a .NET component called
mycomponent
containing a single .NET class named myclass with methods foo and bar.
When used with the
-B option, the word dotnet specifies the name of the
The example creates a .NET component named mycom ponent with two classes:
•
myclass has methods foo and bar
• myclass2 has methods foo2 and bar2
See “Suppo rte d Microsoft .NET Framework Versions” on page 1-4 for a list o f
supported framework versions.
class{...} argument to the mcc
1-20
TheMATLABCompilerBuildProcess
To generate and package an application, the use r:
1 Writes an application o r component in MATLAB
2 Invokes the MATLAB Compiler, which:
a Examines the input MATLAB files and the external dependency
database to determine the complete list of all functions used by the
application or component. As part of this p rocess, MATLAB Compiler
Deploying a Component Using the Magic Square Example
determines which files are not able to be compiled and automatically
excludes them.
b Dete rm ines w hi ch functions are to be made publicly visible (for example,
those that can be called from another product or environment).
c Generates the appropriate interface code files based on the public
function list and the complete function list from the preceding steps. The
interface code g enerated is also dependent on what target the user wants
to create (for example, a Java™ component, a standalone executable, or
a Microsoft
d Packages compilable functions into a CTF archive, creating a file on the
®
Excel®add-in).
user’s disk. This archive is embedded by default in the binary executable.
e Optionally, invokes target specific compiler to generate a binary
application or component from the files in C and the interface code
libraries provided by The MathWorks.
3 Locates the install package for the MATLAB Compiler Runtime (MCR).
4 Collects together the binary, the C TF archive, and the MCR installer (along
with other optional, user-specified files) for the user.
The deployment GUI (
deploytool) automates many o f the steps in the
process for user convenience.
1-21
1 Getting Started
1-22
Deploying a Component Using the Magic Square Example
Magic Square Exa
The following ta
Key Tasks for th
Task
1. Ensure you have the needed files
from the MATLAB programmer
before proceeding.
2. Use the component in a .NET
application. Compile and run the
component to ensure it produces the
same results as your MATLAB code.
3. Archive and distribute the output
to end users.
4. Integ
MATLAB B
existin
5. Verify your .NET application
works as expected in your end user’s
deployment environment.
rate classes generated by the
g .NET applications.
sks are usually performed by the .NET programmer.
e.NETProgrammer
uilder NE product into
mple: .NET Programmer Tasks
Reference
“Gathering Files Needed for
Deployment” on page 1-23
“Using the Component in an
Application” on page 1-25
“Distributing the Component to End
Users” on page 1-28
“Integrating .NET Classes
Generated by MATLAB into a
.NET Application” on page 1-28
“Building and Testing the .NET
Application” on page 1-33
Gathering Files Needed for Deployment
re beginning, verify you have access to the following files, created by
Befo
ATLAB programmer in “Copying the Packag e You Created” on page
the M
1-17. T
copy
• MCR
•
Se
in
o
rom the MATLAB Builder NE help tree (left p ane of MATLAB Product Help).
Tip Although MATLAB Builder NE generates C# code for the Ma gicS quare
component and the sample application is in C#, applications that use the
component do not need to be coded in C#. You can access the component
from any CLS-compliant .NET language. For examples, see Chapter 5,
“Sample Applications (Microsoft
Console.WriteLine("\nMagic square as native array:\n");
// Display the array elements:
for (int i= 0; i < (int)arraySize; i++)
for (int j= 0; j < (int)arraySize; j++)
#endregion
}
}
Deploying a Component Using the Magic Square Example
Console.WriteLine("Element({0},{1})= {2}", i, j, nativeArray[i,j]);
Console.ReadLine(); // Wait for user to exit application
}
catch(Exception exception)
{
Console.WriteLine("Error: {0}", exception);
}
}
2 Build the application using Visual Studio
®
.NET.
Note In the project file for this example, the MWArray assem bly and
the magic square compone nt assembly have been prereferenced. Any
references preceded by an exclamation point require you to remove the
reference and rereference the affected assembly.
Note Microsoft .NET Framework version 2.0 is not supported by Visual
Studio 2003.
a Open the project file for the Magic Square example
(
MagicSquareCSApp.csproj)inVisualStudio.NET.
b If necessary, add a reference to the MWArray component in
See “Supported Microsoft .NET Framework Versions” on page 1-4 for a
list of supported framework versions.
c If necessary, add a reference to the Magic Square component
(
MagicSquareComp), which is in the distrib subfolder.
1-27
1 Getting Started
Distributing the Component to End Users
If you bundled the component as a self-extracting executable, paste it in a
folder on the development machine and run it. If you are using a
bundled with WinZip, unzip and extract the contents to the development
machine.
.zip file
Integrating .NET Classes Generated by MATLAB into a .NET
Application
• “Classes and Methods” on page 1-28
• “Component and Class Naming Conventions” on page 1-29
• “Versioning” on page 1-29
®
• “Managing Data Conversion Issues with M A TLA B
Conversion Classes” on page 1-29
• “Automatic Casting to MATLAB Types” on page 1-31
• “Adding Fields to Data Structure s and Data Structure Arrays” on page 1-32
Builder NE Data
1-28
• “About MATLAB Array Indexing” on page 1-32
• “Accessing Your Component On Another Computer” on page 1-32
Classes and Methods. T he builder project contains the files and settings
needed by the MATLAB Builder NE product to create a deployable .NET
component. A project specifies information about classes and methods,
including the MATLAB functions to be included.
The builder transforms MATLAB functions that are specified in the
component’s project to methods belonging to a managed class.
When creating a component, you must provide one or more class names as
well as a component name. The component name also specifies the name of
the assembly that implements the component. The class name denotes the
name of the class that encapsulates MATLAB functions.
To access the features and operations provided by the MATLAB functions,
instantiate the managed class generated by the builder, and then call the
methods that encapsulate the MATLAB functions.
Deploying a Component Using the Magic Square Example
Component and Class Naming Conventions. Typically you should
specify names for components and classes that will be clear to programmers
who use your components. Fo r example, if you are encapsulating many
MATLAB functions, it helps to determine a scheme of function categories and
to create a separate class for each category. Also, the n ame of each class
should be descriptive of what the class does.
The .NET Framework General Reference recommends the use of Pascal case
for capitalizing the names of identifiers of three or more characters. That
is, the first letter in the identifier and the first letter of each subsequent
concatenated word are capitalized. For example:
MakeSquare
In contrast, MATLAB programmers typically use all lowercase for names
of functions. For example:
makesquare
By convention, the MATLAB Builder NE examples use Pascal case.
Valid characters are any alpha or numeric characters, as well a s the
underscore (
_) character.
Version ing. The builder supports the standard versioning capabilities
provided by the .NET Framework.
Note You can make side-by-side invocations of multiple versions of a
component within the same application only if they access the same version
of the MCR.
Managing Data Conversion Issues with MATLAB Builder NE Data
Conversion Classes. To support data conversion between managed types
and MATLAB types, the builder provides a set of data conversion classes
derived from the abstract class,
MWArray.
When you invoke a method on a component, the input and output parameters
are a derived type of
one of the
MWArray subclasses explicitly, or, in many cases, pass the
MWArray. To pass parameters, you can either instantiate
1-29
1 Getting Started
parameters as a managed data type and rely on the implicit data conversion
feature of .NET Builder.
Overview of Classes and Methods in the Data Conversion Class
Hierarchy
The data conversion classes are built as a class hierarchy that represents the
major MATLAB array types.
Note See “Overview” on page 10-7 for an introduction to the classes and see
MWArray Class Library Reference (available online only) for details about
this class library.
The root of the hierarchy is the MWArray abstract class. The MWArray
class has the following subclasses representing the major MATLAB types:
MWArray anditsderivedclassesprovidethe following functionality:
• Constructors and destructors to instantiate and dispose of MA TLAB arrays
• Properties to get and set the array data
• Indexers to support a subset of MATLAB array indexing
• Implicit and explicit data conversion operators
• General methods
Advantage of Using Data Conversion Classes
The MWArray data conversion classes allow you to pass most native .NET
value types as parameters directly without using explicit data conversion.
There is an implicit cast operator for most native numeric and string types
that will convert the native type to the appropriate MATLAB array.
Deploying a Component Using the Magic Square Example
Automatic Casting to MATLAB Types.
Note Because the conversion process is automatic (in m ost cases), you do not
need to understand the conversion process to pass and return arguments with
MATLAB Builder NE components.
In most instances, if a native .NET primitive or array is used as an input
parameter in a C# program, the builder transparently converts it to an
instance of the appropriate
MWArray class before it is passed on to the
component method. The builder can convert most CLS-compliant string,
numeric type, or multidimensional a rray of these types to an appropriate
MWArray type.
Note This conversion is transparent in C# applications, but might require
an explicit castin g operator in other languages, for example,
op_implicit
in Visual Basic®.
Here is an example. Consider the .NET statement:
result = theFourier.plotfft(3, data, interval);
In this statement the third argument, namely interval,isofthe.NET
native type
1-by-1 double
System.Double. The builder casts this argument to a MATLAB
MWNumericArray type (which is a wrapper class containing a
MATLAB double array).
See “D ata Conversion Rules” on page 10-4 for a list of all the data types that
are supported along with their equivalent types in the MATLAB product.
Note There are some data types commonly used in the MATLAB product
that are not available as native .NET types. Examples are cell arrays,
structure arrays, and arrays of complex numbers. Represent these array
types as instances of
MWCellArray, MWStructArray,andMWNumericArray,
respectively.
1-31
1 Getting Started
Adding Fields to Data Structures and Data Structure Arrays. When
adding fields to data structures and data structure arrays, d o so using
standard programming techniques. Do not use the
set command as a
shortcut.
For examples of how to correctly add fields to data structures and data
structure arrays, see the programming examples in Chapter 4, “Sample
Applications (C#)” and Chapter 5, “Sample Applications (Microsoft
®
Visual
Basic .NET)”.
About MATLAB Array Indexing. .NET Builder provides indexers to
support a subset of MATLAB array indexing.
Note If each element in a large array returned by a .NET Builder component
is to be indexed, the returned MATLAB array should first be converted to
a native array using the
toArray() method. This results in much better
performance.
1-32
Don’t keep the array in MATLAB type; convert it to a native array first. See
Chapter 1 , “Getting Started” for an example of native type conversion.
Accessing Your Component On Another Computer. To implement your
.NET component on a computer other than the one on which it was built:
1 If the component is not already installed on the machine where you want
to develop your application, run the self-extracting executable that you
created in “Deploying a Component Using the Magic Square Example”
on page 1-9.
This step is not necessary if you are developing your application on the
same machine where you created the .NET component.
2 Reference the .NET component in your Microsoft
®
Visual Studio®project or
from the command line of a CLS-compliant compiler.
Deploying a Component Using the Magic Square Example
See “Supported Microsoft .NET Framework Versions” on page 1-4 for a
list of supported framework versions.
3 Instantiate the generated .NET Builder classes and call the class methods
as you would with any .NET class. To marshal data between the native
.NET types and the MATLAB array type, you need to use either the
MWArray data conversion classes or the MWArray native API. See MWArray
Class Library Reference (available online only) for details about the
MWArray API for this class library.
Building and Testing the .NET Application
1 Build and test the .NET application as you would any application.
2 Create an application installation package for end users that includes
the files required for the .NET Builder components that encapsulate the
MATLAB functions.
1-33
1 Getting Started
Next Steps
After you create and distribute the initial application, you probably want to
continue to enhance it. Pointers to documentation detailing some of the more
commontasksyouperformasyoudevelopyour application are listed here.
Writing .NET applications that
can access .NET methods that
encapsulate MATLAB code
Sample applications that access
methods developed in MATLAB
Deploying .NET components over
the Web
Creating a remotable component
or learning about remotable
components
Chapter 3, “Using Components
Created by the MATLAB
NE Product”
Chapter 6, “Deploying a MATLAB
Figure Over the Web Using
WebFigures”
Chapter 8, “Sharing Components
Across Distributed Applications
Using .NET Remoting”
®
®
Visual
Builder
1-34
WritingDeployable
MATLAB Code
• “The MATLAB Application Deployment Products” on page 2-2
• “Building Your Application with the Application Deployment Products and
the Deployment Tool” on page 2-4
• “Guidelines for Writing Deployable M ATLA B Code” on page 2-10
• “Working with MATLAB Data Files Using Load and Save” on page 2-14
2
2 Writing Deployable MATLAB
®
Code
The MATLAB Application Deployment Products
The MATLAB S
Product
MATLAB
Compiler
MATLAB
Builder NE
MATLAB
Builder JA
MATLAB expert
No IT experience
MATLAB
Programmer
The followin
No access to IT systems
g tables summarizes the target applications supported by each
product.:
uite of Applic ation Deployment Products
Target
CandC++
Create
Standalone
Executables?
Create
Function
Libraries?
YesYesYesNo
standalones
and libraries
C# .NET
NoYesYesYes
components
Visual
Basic COM
components
Java
NoYesYesYes
components
Develops model
Uses the builder tools to create a
component that is given to the
business service developer
Create
Applications
Create Web
Applications?
with
Graphics?
2-2
MATLAB
Builder EX
Microsoft
Excel add-ins
NoYesYesNo
The MATLAB®Application Deployment Products
The MATLAB®Application Deployment Products
Each of the builder products uses the MATLAB Compiler core code to create
deployable components.
2-3
2 Writing Deployable MATLAB
®
Code
Building Your Application with the Application Deployment
Products and the
In this section...
“What Is the Difference Between the Deployment Tool and the mcc
Command Line?” on page 2-4
“How Does MATLAB®Compiler Software Build My Application?” on page
2-4
“What You Should Know About the Dependency Analysis Function
(depfun)” on page 2-5
“Compiling MEX-Files, DLLs, or Shared Libraries” on page 2-6
“The Role of the Component Technology File (CTF Archive)” on page 2-7
Deployment Tool
What Is th
and the m
Using th
would i
Deploy
custom
the sa
Using
• Perf
• Main
• Pac
Ho
Ap
MA
nvoke using the MATLAB Compiler
ment Tool interactive menus and dialogs build
ized to your specification. As such, your MATLAB code is processe d
me way as if you were compiling it using
the Deployment Tool, you:
orm related deployment tasks with a single intuitive GUI.
tain related information in a convenient project file. Your project
e persists between sessions. Your previous project loads automatically
stat
n the Deployment Tool starts. You load previously stored compiler
whe
jects from a prepopulated menu.
pro
kage applications for distribution.
w Does MATLAB Compiler Software Build My
plication?
TLAB Compiler software:
e Difference Between the Deployment Tool
cc Command Line?
e D eploym ent Tool (
deploytool) GUI, you perform any function you
mcc command-line interface. The
mcc commands that are
mcc.
2-4
Building Your Application with the Application Deployment Products and the Deployment Tool
1 Parses command-line arguments and classifies by type the files you provide.
2 Analyzes files for dependencies using the Dependency Analysis Function
(
depfun). Dependencies affect deployability and originate from file
contents—functions called by the file. Deployability is affected by:
• File type — MATLAB, Java, MEX, and so on.
• File location — MATLAB, MATLAB toolbox, user code, and so on.
• File deployability — Whether the file is deployable outside of MATLAB
For more information about
depfun, see “What You Should Know About
the D ependency Analysis Function (depfun)” on page 2-5.
3 Validates MEX-files. In particular, me xFun ction entry points are verified).
For more details about MEX-file processing, see “Compiling MEX-Files,
DLLs, or Shared Libraries” on page 2-6.
4 Creates a CTF archive from the input files and their dependencies.
For more details about CTF archives see “The Role of the Component
Technology File (CTF Archive)” on page 2-7.
5 Generates target-specific wrapper code. For example, the wrapper for a C
main function is very different than the wrapper for a Java interface class.
6 Invokes a third-party target-specif ic compiler to create the appropriate
binary software com ponent (a standalone executable, a Java JAR file,
and so on).
For details about how MATLAB Compiler software builds your deployable
component, see “The MATLAB
®
Compiler Build Process” on page 1-20.
What You Should Know About the Dependency
Analysis Function (depfun)
MATLAB Compiler uses a dependency analysis function (depfun)to
determine the list of necessary files to include in the CT F package. In some
cases, this process includes an large number of files. This is often true when
MATLAB object classes exist in the compilation and
overloaded methods at compile time. Dependency analysis also processes
include/exclude files on each pass (see the mcc flag “-a Add to Archive”).
depfun cannot resolve
2-5
2 Writing Deployable MATLAB
Tip To improve compile time performance and lessen application size, prune
the path with “-N Clear Path”, “-p Add Directory to Path”, or by specifying
Toolboxes on Path in the
depfun searches for executable content such as:
• MATLAB files
• P-files
®
Code
deploytool Settings
• Java classes and
.fig files
•
.jar files
• MEX-files
depfun does not search for data files of any kind (except MAT files). You
must manually
include data files.
Compiling MEX-Files, DLLs, or Shared Libraries
When you compile MATLAB functions containing MEX-files, ensure
that
depfun can find them—doing so allows you to avoid many common
compilation problems. In particular, note that:
•
depfun cannot examine MEX-files, DLLs, or shared libraries to determine
their dependencies. Explicitly include all binaries these files require
either with the
Deployment Tool unde r Settings.
• If you have any doubts that
a MEX-file, DLL, or shared library—manually include it. Do this with
either the
the Deployment Tool under Settings.
• Not all functions are compatible with MATLAB Compiler. Check the file
mccExcludedFiles.log after your build completes. This file lists all
functions called from your application that you cannot deploy.
mcc -a option or the options on the Advanced tab in the
depfun can find a MATLAB function called by
mcc -a option or by using the options on the Advanced tab in
2-6
Building Your Application with the Application Deployment Products and the Deployment Tool
TheRoleoftheComponentTechnologyFile(CTF
Archive)
Each application or shared library produced by MATLAB Compiler has an
associated Component Technology File (CTF) archive. The archive contains
all the MATLAB based content (MATLAB files, MEX-files, and so on)
associated with the compo ne nt.
MATLAB Compiler also embeds a CTF) archive in each generated binary.
The CTF houses all deployable files. All MATLAB files encrypt in the CTF
archive using the Advanced Encryption Standard (AES) cryptosystem .
If you choose the extract the CTF archive as a separate file the files remain
encrypted. For more information on how to extract the CTF archive refer to
the references in the following table.
Information on CTF Archive Embedding/Extraction and Component
Cache
Product
MATLAB Compiler“Overriding Default CTF Archive
MATLAB Builder NE“Overriding Default CTF Archive
MATLAB Builder JA“Using M CR Component Cache and
MATLAB Builder EX“Overriding Default CTF Archive
Refer to
Embedding Using the MCR
Component Cache”
Embedding for Components Using
the MCR Component Cache” on page
3-24
MWComponentOptions”
Embedding for Components Using
the MCR Component Cache”
2-7
2 Writing Deployable MATLAB
®
Code
2-8
Building Your Application with the Application Deployment Products and the Deployment Tool
Additional Details
Multiple CTF archives, such as those generated with C OM, .NET, or Excel
components, can coexist in the same user application. You cannot, however,
mix and match the MATLAB files they contain. You cannot combine
encrypted and compressed MATLAB files from multiple CTF archives into
another CTF archive and distribute them.
All the M ATLA B files from a given CTF archive associate with a unique
cryptographic key. MATLAB files with different keys, placed in the same
CTF archive, do not execute. If you want to generate another application
with a different mix of MATLAB files, recompile these MATLAB files into a
new CTF archive.
MATLAB Compiler deleted the CTF archive and generated binary following
a failed compilation, but only if these files did not exist before compilation
initiates. Run
CautionRelease Engineers and Software Configuration Managers:
Do not use build procedures or processes that strip shared libraries on CTF
archives. If you do, you can possibly strip the CTF archive from the binary,
resulting in run-time errors for the driver application.
help mcc -K for more info rmation.
®
2-9
2 Writing Deployable MATLAB
®
Code
Guidelines for Writing Deployable MATLAB Code
In this section...
“Compiled Applications Do Not Process MATLAB Files at Runtime” on
page 2-10
“Do Not Rely on Changing Directory or Path to Control the Execution of
MATLAB Files” on page 2-11
“Use ismcc and isdeployed Functions To Execute Deployment-Specific Code
Paths” on page 2-11
“Gradually Refactor Applications That Depend on Noncom pilable
Functions” on page 2-12
“Do Not Create or Use Nonconstant Static State Variables” on page 2-12
Compiled Applications Do Not Process MATLAB Files
at Runtime
The MATLAB Compiler was designed so that you can deploy locked down
functionality. Deployable MATLAB files are suspended or frozen at the
time MATLAB Compiler encrypts them—they do not change from that point
onward. This does not mean that you cannot deploy a flexible application—it
means that you must design your application with flexibility in mind.Ifyou
want the end user to be able to choose between two different methods, for
example, they both must be compiled in.
2-10
The MCR only works on MATLAB code that was encrypted when the
component was built. Any function or process that dynamically generates
new MATLAB code will not work against the MCR.
Some MATLAB toolboxes, such as the Neural Network Toolbox™ product,
generate MATLAB code dynamically. Because the MCR only executes
encrypted MATLAB files, and the Neural Network Toolbox generates
unencrypted MATLAB files, some functions in the Neural Network Toolbox
cannot be deployed.
Similarly, functions that need to examine the contents of a MATLAB function
file cannot be deployed.
HELP, for example, is dynamic and not available in
Guidelines for Writing Deployable MATLAB®Code
deployed mode. You can use LOADLIBRARY in deployed mode if you provide
it with a MATLAB function prototype.
Instead of compiling the function that generates the MATLAB code and
attempting to deploy it, perform the following tasks:
1 Run the code once in MATLAB to obtain your generated function.
2 Compile the MATLAB code with MATLAB Compiler, including the
generated function.
Tip Another alternative to using EVAL or FEVAL is using anonymous function
handles.
If you require the ability to create MATLAB code for dynamic runtime
processing, your end-users must have an installed copy of MATLA B.
Do Not Rely on Changing Director y or Path to Control
the Execution of MATLAB Files
In general, good programming practices advise against redirecting a program
search path dynamically within the code. Many programmers are prone
to this behavior since it mimics the actions they usually perform on the
command line. However, this can lead to problems when deploying code.
For example, in a deployed application, the MATLAB and Java paths are
fixed and cannot change. Therefore, any attempts to change these paths
(using the
If you find you cannot avoid placing
ismcc and isdeployed. See the next section for details.
cd command or the addpath command) fails
addpath calls in your MATLAB code, use
Use ismcc and i sdeployed Functions To Execute
Deployment-Specific Code Paths
The isdeployed function allows you to specify which portion of your MATLAB
code is deployable, and which is not. Such specification minimizes your
compilation errors and helps create m ore efficient, maintainable code.
2-11
2 Writing Deployable MATLAB
For example, you find it unavoidable to use addpath when writing your
startup.m.Usingismcc and isdeployed, you specify when and what is
compiled and executed.
®
Code
For an example of using
a Standalone Application”.
isdeployed, see “Passing Arguments to and from
Gradually Refactor Applications That Depend on
Noncompilable Functions
Over time, refactor, streamline, and modul ari ze MATLAB code containing
non-compilable or non-deployable functions that use
Your eventual goal is “graceful degradation” of no n-deploya ble code. In
other words, the code must present the end user with as few obstacles to
deployment as possible until it is practically eliminated.
Partition your code into design-time and run-time code sections:
• Design-time code is code that is currently evolving. Almost all code goes
through a phase of perpetual rewriting, debugging, and optimization. In
some toolboxes, such as the Neural Network Toolbox product, the code goes
through a period of self-training as it reacts to various data permutations
and patterns. Such code is almost never designed to be deployed.
• Run-time code, on the other hand, has solidified or become stable—it is in a
finishedstateandisreadytobedeployedbytheenduser.
Consider creating a separate directory for code that is not meant to be
deployed or for code that calls undeployable code.
ismcc and isdeployed.
2-12
Do Not Create or Use Nonconstant Static State
Variables
Avoid using the following:
• Global variables in MATLAB code
• Static variables in MEX-files
• Static variables in Java code
Guidelines for Writing Deployable MATLAB®Code
The state of these variables is persistent and shared with everything in the
process.
Persistent variables can cause problems because the MCR process runs in a
single thread. You cannot load more than one of these non-constant, static
variables into the same process. In addition, these static variables do not
work well in multithrea ded applications.
If you must u se static variables, bind them to instances. For example,
defining instance variables in a Java class is preferable to defining the
variable as
static.
Note This guideline does not apply to MATLAB Builder EX customers.
When programming with Microsoft Excel, you can assign global variables to
large matrices that persist between calls.
2-13
2 Writing Deployable MATLAB
®
Code
Working with MATLAB Data Files Using Load and Save
If you r deployed application uses MATLAB data files (MAT-files), it is helpful
to code
processing.
LOAD and SAVE functions to manipulate the data and store it for later
• Use
• Specify the data file by full path name or relative to
• All MAT-files are unchanged after
For more information about C TF archives, see “The Role of the Component
Technology File (CTF Archive)” on page 2-7.
Use the following example as a template for manipulating your MATLAB
data inside, and outside, of MATLAB.
isdeployed to determine if your code is running in or out of the
MATLAB workspace.
ctfroot.
mcc runs. These files are not encrypted
when written to the CTF archive.
Using Load/Save Functions to Process MATLAB Data
for Deployed Applications
The following example specifies three MATLAB data files:
•
user_data.mat
• userdata/extra_data.mat
• ../externdata/extern_data.mat
Compile ex_loadsave.m with the following mcc command:
2-14
mcc -mvC ex_loadsave.m -a 'user_data.mat' -a
'./userdata/extra_data.mat' -a
'../externdata/extern_data.mat'
loadsave.m
ex_
function ex_loadsave
Working with MATLAB Data Files Using Load and Save
% This example shows how to work with the
% "load/save" functions on data files in
% deployed mode. There are three source data files
% in this example.
%user_data.mat
%userdata/extra_data.mat
%../externdata/extern_data.mat
%
% Compile this example with the mcc command:
%mcc -mC ex_loadsave.m -a 'user_data.mat' -a
%'./userdata/extra_data.mat'
%-a '../externdata/extern_data.mat'
% All the folders under the current main MATLAB file directory will
%be included as
% relative path to ctfroot; All other folders will have the
%folder
% structure included in the ctf archive file from root of the
%disk drive.
%
% If a data file is outside of the main MATLAB file path,
%the absolute path will be
% included in ctf and extracted under ctfroot. For example:
Using Components Created
bytheMATLABBuilder
NE Product
To use a .NET component built and packaged by the MATLAB Builder NE
product, perform the following tasks.
• “Installing the Components on the Development Machine ” on page 3-2
• “Specifying Component Assembly and Namespace” on page 3-3
• “Creating an Instance of a Class” on page 3-4
• “Using Dispose to Explicitly Free Resources” on page 3-5
• “Improving Data Access Using the MCR User Data Interface and
MATLAB
• “Dynamically Specifying Run-Time Options to the MCR” on page 3-11
• “Accessing Real or Imaginary Components Within Complex Arrays” on
page 3-14
• “Blocking Execution of a Console Application that Creates Figures” on
page 3-17
• “Using MATLAB API Functions in a C# Program” on page 3-20
• “Handling Errors” on page 3-22
• “Overriding Default CTF Archive E mbedding for Components Using the
MCR Component Cache” on page 3-24
• “Using Enhanced XML Documentation Files” on page 3-26
®
Builder NE” on page 3-6
3 Using Components Created by the MATLAB
®
Builder™ NE Product
Installing the C omponents on the Development Machine
To use components on a particular development machine, you deploy .dll file
(
componentname.dll) along with the MCR (if not already installed). You must
do this even if you are not using the packaging process outlined in “Packaging
Your Component (Optional)” on page 1-16.
1 Unpack and install the components on the machine.
2 Copy compone
run it.
You must rep
be used.
eat these steps for each machine where the component will
ntname
.exe to a folder on the development machine, and
3-2
Specifying Component Assembly and Namespace
Specifying Component Assembly and Namespace
To use the component assembly generated using the MATLAB Builder NE
product from the client application, you must
• Reference the MATLAB data conversion assembly and specify the
namespace in your application, as shown:
using MathWorks.MATLAB.NET.Arrays;
• Reference the namespace for the builder assembly generated for your
particular component and specify the namespace in your application, for
example:
using MyComponentName;
Note The builder supports nested namespaces.
Suppose you named the component you created MyComponentName and you
want to use it in a program named
at the beginning of
using System;
using MathWorks.MATLAB.NET.Arrays;
using MyComponentName;
MyApp.cs:
MyApp.cs. Here are the statements to use
3-3
3 Using Components Created by the MATLAB
®
Builder™ NE Product
Creating an Instance of a Class
As with any .NET class, you need to create an instance of the classes you
create with the MATLAB Builder NE product before you can use them in
your program.
Suppose you build a component with a class named
is an example of creating an instance of that class:
MyComponentClass classInstance = new MyComponentClass();
See “How the MCR Is Shared Among Classes” on page 1-17 for information
about what happens when you instantiate classes.
MyComponentClass.Here
3-4
Using Dispose to Explicitly Free Resources
Note As of R2009b, native memory management for mxA rra y is automatically
handled by .NET’s CLR memory manager. There is no longer a reason to
manually disable native memory management when working with
Calls to disable memory management will result in a null operation.
Usually the Dispose method is called from a finally sectioninatry-fina lly
block as you can see in the following example:
try
{
/* Allocate a huge array */
MWNumericArray array = new MWNumericAr ray(1000,1000);
.
.(use the array)
.
}
finally
{
/* Explicitly dispose of t he managed array and its */
/* native resources */
if (null != array)
{
array.Dispose();
}
}
Using Dispose to Explicitly Free Resources
mxArray.
The statement array.Dispose() frees the memory allocated by both the
managed wrapper and the native MATLAB array.
The
MWArray class provides two disposal methods: Dispose and the static
method
disposes of either a single
DisposeArray.TheDisposeArray method is more general in that it
MWArray or an array of arrays of type MWArray.
3-5
3 Using Components Created by the MATLAB
®
Builder™ NE Product
Improving Data Access Using the MCR User Data Interface
and MATLAB Builder NE
This feature allow s data to be shared between an MCR instance, the MATLAB
code running on that MCR, and the wrapper code that created the MCR.
Through calls to the MCR User Data interface API, you access MCR data by
creating a per-MCR-instance associative array of
mapping from string keys to
butarenotlimitedto:
• You need to supply run-time confi guration information to a client
running an application created with the Parallel Computing Toolbox™
software. Configuration information may be supplied (and changed) on a
per-execution basis. For example, two instances of the same application
may run simultaneously with different configuration files.
• You want to initialize the MCR with constant values that can be accessed
by all your MATLAB applications.
mxArray values. Reasons for doing this include,
mxArrays, consisting of a
• You want to set up a global workspace — a global variable or variables that
MATLAB and your client can access.
• You want to store the state of any variable or group of variables.
MATLAB Builder NE software supports a per-MCR instance state access
throughanobject-orientedAPI.Unlike MATLAB Compiler, access to a
per-MCR instance state is optional, rather than on by default. You can access
this state by adding
deployment project or by specifying them on the command line.
For more information, see“Improving Data Access Using the MCR User Data
Interface” in the MATLAB Compiler User’s Guide.
setmcruserdata.m and getmcruserdata.m to your
Code Snippets
The following code snippets demonstrate storing and retrieving the MCR
state while working with the
MagicMatrix Function
function magicmatrix
MagicMatrix function.
3-6
Improving Data Access Using the MCR User Data Interface and MATLAB®Builder™ NE
key = 'MagicMatrix';
m = getmcruserdata(key);
disp(m);
m=m+1;
setmcruserdata(key, m);
// Create the key and the data
string key = "MagicMatrix" ;
double[,] magicData = { {8, 1, 6},
{3,5,7},
{4,9,2}};
// Create an instance of the component created by the builder
MagicMatrix m = new MagicMatrix();
// Store a magic matrix under the key "MagicMatrix"
m.setmcruserdata(key, (MWNumericArray)magicData);
Calling getmcruserdata
// Create the key, declare a variable to receive the value
String key = "MagicMatrix" ;
Object[] result = null;
// Create the component class (and the associated MCR instance)
m = new magicmatrix();
// Retrieve the value stor ed under the key in the map owned by the MCR
// associated with the component m.
result = m.getmcruserdata(1, key);
Example
The following is an end-to-end example showing how to build, run, and work
with the
magicmatrix application and the MCR User Data interface API. This
3-7
3 Using Components Created by the MATLAB
function retrieves the numeric matrix stored under the key MagicMatrix,
adds 1 to it and stores the result back into the per-MCR instance data map,
overwriting the previous value.
MagixMatrix Function
function magicmatrix
key = 'MagicMatrix';
m = getmcruserdata(key);
disp(m);
m=m+1;
setmcruserdata(key, m);
Building
This command assumes the existence of a component named
Improving Data Access Using the MCR User Data Interface and MATLAB®Builder™ NE
udata.cs
// udata.cs
// Demonstrate the MCR User Data interface API in the builder.
using System;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using MagicMatrixComponent;
namespace MathWorks.Demo.UserData
{
class MagicMatrixTest
{
[STAThread]
static void Main(string[] args)
{
string key = "MagicMatri x";
MWArray result = null;
try
{
double[,] magicData = { {8, 1, 6},
{3, 5, 7},
{4, 9, 2} };
// Create an instance of the component
// created by the builder
MagicMatrix m = new MagicMatrix();
// Call the functions exported by the component, using
// per-MCR instance state t o communicate between
// the C# wrapper code and the executing MATLAB functions.
//
// First, store a magic matrix under the key "MagicMatrix"
m.setmcruserdata(key, (MWNumericArray)magicData);
// Add 1 to the magic matrix, display it, and save
// the new value in the per-MCR instance data.
3-9
3 Using Components Created by the MATLAB
}
catch(Exception exception)
{
}
}
}
}
®
Builder™ NE Product
m.magicmatrix();
// Retrieve the new value stored under "MagicMatrix."
result = m.getmcruserdata(key);
// Print the result matrix
Console.WriteLine(result);
Console.WriteLine("Error: {0}", exception);
3-10
Dynamically Specifying Run-Time Options to the MCR
Dynamically Specifying Run-Time Options to the MCR
In this section...
“What Run-Time Options Can You Specify?” on page 3-11
“Getting MCR Option V alues Using MW MCR” on page 3-11
What Run-Time Options Can You Specify?
As of R2009a, you can pass MCR run-time options -nojvm and -logfile
to MATLAB Builder NE from a client application using the assembly-level
attributes
calling methods of the
Getting MCR Option Values Using MWMCR
The MWMCR class provides several methods to get MCR option values. The
following table lists methods supported by this class.
NOJVM and LOGFILE. you can retrieve values of these attributes by
MWMCR clas s to access MCR attributes and MCR state.
MWMCR Method
MWMCR.IsMCRInitialized()
MWMCR.IsMCRJVMEnabled()
MWMCR.GetMCRLogFileName()
Purpose
Returns true if MCR is initialized,
otherwise returns
Returns true if MCR is launched
with Java Virtual Machine (JVM),
otherwise returns
Returns the name of the log file
passed with the
false.
false.
LOGFILE attribute.
Default MCR Options
If you pass no MCR options (you provide no attributes), the MC R is launched
with default option values:
MCR Run-Time Option
Java Virtual Machine (JVM)
Log file usage
Default Option Values
NOJVM(false)
LOGFILE(null)
3-11
3 Using Components Created by the MATLAB
These options are all write-once, read-only properties.
Use the following attributes to represent the MCR options you want to modify.
®
Builder™ NE Product
MWMCR Attribute
NOJVM
Purpose
Lets users launch MCR with or
without a JVM. It takes a Boolean
as in p ut. For example,
NOJVM(true)
launches MCR without a JVM.
LOGFILE
Lets users pass the name of
a log file, taking the file
name as input. For example,
LOGFILE("logfile3.txt") .
Example: Passing MCR Option Values from a C# Application.
Following is an example of how MCR option values are passed from a
client-side C# application:
[assembly: NOJVM(false), LOGFILE("logfile3.txt")]
namespace App1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("In side main...");
try
{
myclass cls = new myclass();
cls.hello();
Console.WriteLine("Done!!");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
3-12
Dynamically Specifying Run-Time Options to the MCR
}
3-13
3 Using Components Created by the MATLAB
®
Builder™ NE Product
Accessing Real or Imaginary Components Within Complex
Arrays
In this section...
“Extracting R eal or Imaginary Components” on page 3-14
“Returning Values with Component Indexing” on page 3-14
“Assigning Values with Component Indexing” on page 3-15
“Converting M ATLA B Arrays to .NET Arrays Using Component Indexing”
on page 3-15
Extractin
When you a
imaginar
componen
and imag
It is also possible, when calling a method to return or assign a value, to
extract only the real or imaginary component of a complex matrix. To do this,
call the appropriate component indexing method.
This section describes how to use component indexing when returning or
assigning a v alue, and also describes how to use component indexing to
convert MATLAB arrays to .NET arrays using the
methods.
g Real or Imaginary Components
ccess a complex array (an array made up of both real and
y data), you extract both real and imaginary parts (called
ts) by default. This method call, for example, extracts both real
Implementing Component Indexing on Sparse Complex
Numeric Arrays (Microsoft V isual Studio 8 and Later)
To return the real or imaginary component of a sparse complex numeric array,
call the
.real or .imaginary method M WArrayComponent as follows:
complexResult= sparseC
complexResult = sparse
omplexDouble[MWArrayComponent.Real, 4, 3];
ComplexDouble[MWArrayComponent.Imaginary, 4, 3];
Assigning Values with Component Indexing
The following section illustrates how to assign values to full and sparse arrays
using component indexing.
Implementing Compon
entIndexingonFullComplexNumeric
Arrays
To assign the real or
call the
.real or .i
matrix[MWArrayComponent.Real, 2, 2]= 5;
matrix[MWArrayComponent.Imaginary, 2, 2]= 7:
imaginary component to a full complex numeric array,
maginary
method MWArrayComponent as follows:
Converting MATLAB Arrays to .NET Arrays Using
Component Indexing
The following section illustrates how to use the ToArray and ToVector
methods to convert full and sparse MATLAB arrays and vectors to .NET
arrays and vectors respectively.
Converting MATLAB Arrays to .NET Arrays
To convert MATLAB arrays to .NET arrays call the toArray method with
either the
follows:
this method from an interactive program, such as Microsoft Excel, can hang
the application. This method should be called only from console-based
programs.
Code Fragment: Using WaitForFiguresToDie to Block
Execution
ThefollowingexampleillustratesusingWaitForFiguresToDie from a .NET
application. The example uses a .NET component created by the MATLAB
Builder NE product; the object encapsulates MATLAB code that draws a
simple plot.
1 Create a work folder for your source code. In this example, the folder is
D:\work\plotdemo.
2 In this folder, create the following MATLAB fil e:
®
Builder™ NE Product
3-18
drawplot.m
function drawplot()
plot(1:10);
3 Use MATLAB Builder NE to create a .NET component with the following
properties:
Component name
Class name
4 Createa.NETprograminafilenamedrunplot with the following code:
using Figure.Plotter;
public class Main {
public static void main (String[] args) {
try {
plotter p = new Plotter();
try {
Figure
Plotter
Blocking Execution of a Console Application that Creates Figures
p.showPlot();
p.WaitForFiguresToDie();
}
catch (Exception e) {
console.writeline(e);
}
}
}
}
5 Compile the application.
When you run the application, the program displays a plot from 1 to 10 in a
MATLAB figure window. The application ends when you dismiss the figure.
Note To see what happens without the call to WaitForF igur esToDie,
comment out the call, rebuild the application, and run it. In this case, the
figure is drawn a nd is im mediately destroyed as the application exits.
3-19
3 Using Components Created by the MATLAB
®
Builder™ NE Product
UsingMATLABAPIFunctionsinaC#Program
In this section...
“Overview” on page 3-20
“Example: Using functions engOpen and engEvalString from the MATLAB
Engine API in a C# Program” on page 3-20
Overview
You include functions from MATLAB APIs, such as the E ngine API, in
your C# code by using the
libeng.dll (written in unmanaged C) and then declaring those functions as
C# equivalents. The imported Engine functions are called using the
mechanism, as illustrated in the example below.
Example:Using functions engOpen and
engEvalString from the MATLAB Engine API in a C#
Program
DllImport attribute to import functions from
P/Invoke
3-20
1 Open Microsoft Visual Studio .NET.
2 Select File > New > Project.
3 Select
4 Auto-generated code appears. Replace the auto-generated code with this
Visual C# Application s intheleftpaneandConsole Application
in the
code and run:
right pane. Click OK.
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication8
{
class MatlabEng
{
[DllImport("libeng.dll")]
Using MATLAB API Functions in a C# Program
static extern IntPtr eng Open(string startcmd);
[DllImport("libeng.dll")]
static extern IntPtr eng EvalString(IntPtr engine,
string Input);
public MatlabEng()
{
IntPtr engine;
engine = engOpen(null);
if (engine == IntPtr.Zero)
throw new NullReferenceException("Failed to
Initialize Engine");
engEvalString(engine, "surf(peaks)");
}
~MatlabEng()
{
}
}
class StartProg
{
public static void Main( )
{
}
}
}
MatlabEng mat = new MatlabEng();
3-21
3 Using Components Created by the MATLAB
Handling Errors
As with managed code, any errors that occur during execution of an MATLAB
function or during data conversion are signaled by a standard .NET exception.
Like any other .NET application, an application that calls a method generated
by the MATLAB Builder NE product can handle errors by either
• Catching and handling the exception locally
• Allowing the calling method to catch it
Here are examples for each way of handling errors.
®
Builder™ NE Product
In the
GetPrimes example the method itself handles the exception.
public double[] GetP
{
MWArray primes= nul
MyPrimesClass myPr
try
{
myPrimesClass= ne
primes= myPrimesC
return (double[]
ToVector(MWArra
}
catch (Exceptio
{
Console.WriteL
return new doub
}
}
rimes(int n)
l;
imesClass= null;
w MyPrimesClass();
lass.myprimes((double)n);
)(MWNumericArray)primes).
yComponent.Real);
n ex)
ine("Exception: {0}", ex);
le[0];
In the n ext example, the method that calls myprimes does not catch the
exception. Instead, its calling method (that is, the method that calls the
method that calls
public double[] GetPrimes(int n)
{
MWArray primes= null;
myprimes) handles the exception.
3-22
MyPrimesClass myPrimesClass= null;
try
{
myPrimesClass= new MyPrimesClass();
primes= myPrimesClass.myprimes((double)n);
return (double[])(MWNumericArray)primes).
ToVector(MWArrayComponent.Real);
}
catch (Exception e)
{
throw;
}
}
Handling Errors
3-23
3 Using Components Created by the MATLAB
®
Builder™ NE Product
Overriding Default CTF Archive Embedding for Components
Using the MCR Component Cache
As of R2008b, CTF data is automatically embedded directly in .NET and COM
components by default. In order to extract the CTF archive manually, you
must build the component using the
mcc -C option.
If you do not use the
add environment variables to specify various options, such as:
• Defining the location where you want the CTF archive to be extracted
• Adding diagnostic error printing options that can be used when extracting
the CTF, for troubleshooting purposes
• Tuning the MCR component cache size for performance reasons.
Use the following environment variables to change these settings.
Environment Variable
MCR_CACHE_ROOTWhen set to the location of
MCR_CACHE_VERBOSE
PurposeNotes
where you want the CTF
archive to be extracted, this
variable overrides the default
per-user component cache
location.
When set, this variable prints
details about the component
cache for diagnostic reasons.
This can be very helpful
if problems are encountered
during CTF archive extraction.
mcc -C option to generate a separate CTF file, you can
Not applicable
Not applicable
MCR_CACHE_SIZE
3-24
When set, this variable
overrides the default
component cache size.
The initial limit for this
variable is 32M (megabytes).
This may, however, be changed
after you have set the variable
the first time. Edit the file
.max_size, which resides in
the file designated by running
Overriding Default CTF Archive Embedding for Components Using the MCR Component Cache
Environment Variable
PurposeNotes
the mcrcachedir command,
with the desired cache size
limit.
3-25
3 Using Components Created by the MATLAB
®
Builder™ NE Product
Using Enhanced XML Documentation Files
Every MATLAB® Builder NE component includes a readme.txt file in the
src and distrib directories. This file outlines the contents of auto-generated
documentation templates included with your built component. The
documentation templates are HTML and XML files that can be read and
processed by any number of third-party tools.
•
MWArray.xml — This file describes the MWArray data conversion classes
and their associated methods. Documentation for
their methods are available here.
component. Using a third party docume ntationtool,youcancombinethis
file with
packaged with the component assembly for distribution to end users.
•
component_name_overview.html — Optionally include this file in the
generated documentation file. It contains an o ve rview of the steps needed
to access the component and how to use the data conversion classes,
contained in the
generated component and return the results.
MWArray.xml to produce a complete documentation file that can be
MWArray class hierarchy, to pass arguments to the
MWArray classes and
3-26
Sample Applications (C#)
Note The examples for the MATLAB Builder NE product are in
matlabroot\toolbox\dotnetbuilder\Examples\VSversionnumber,where
matlabroot is the folder where the MATLAB product is installed andVSversionnumber specifies the version of Microsoft Visual Studio .NET you
are using (in this case
installed, you can load projects for all the examples by opening the solution