On this page…
About This Example
Magic Square Example: MATLAB Programmer Tasks
Using the Command Line to Create .NET Components
Magic Square Example: .NET Programmer Tasks
About This Example
This example shows you how to transform a simple M-code function into a deployable MATLAB Builder NE component.
The Magic Square example shows you how to create a .NET component named MagicSquareComp, which contains the magic class and other files needed to deploy your application.
The magicSquareClass wraps a MATLAB 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, magic, that you can use to create magic squares of any dimension.
Note The examples here use the Windows deploytool 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 mcc reference page.
Note If you wish to create a remotable component, and for information about what this entails, see Sharing Components Across Distributed Applications Using .NET Remoting.
Back to Top of Page Back to Top
Magic Square Example: MATLAB Programmer Tasks
The MATLAB programmer usually performs the following tasks.
Key Tasks for the MATLAB Programmer
Task Reference
1. Start the product. Starting the Deployment Tool
2. Prepare to run the example by copying the MATLAB example files into a work folder. Copying the Example Files
3. Test the M-code to ensure it is suitable for deployment. Testing the M-File You Want to Deploy
4. Create a .NET component (encapsulating your M-code in a .NET class) by running the Build function in deploytool. Building Your Component
5. Prepare to run the Packaging Tool by determining what additional files to include with the deployed component. Packaging Your Component (Optional)
6. Copy the output. Copying the Package You Created
Note The MATLAB Builder NE examples are in matlabroot\toolbox\dotnetbuilder\Examples\VS8\NET. This example assumes the work folder is on drive D:.
Starting the Deployment Tool
Access the MATLAB Builder NE product through the Deployment Tool GUI (deploytool) or through the mcc function of the MATLAB Compiler product. deploytool is the GUI front end for mcc, which executes MATLAB Compiler software.
This example uses deploytool. If you want to use mcc, see the mcc reference page for complete reference information.
To start this product:
1.
Start MATLAB.
2.
Type deploytool at the MATLAB command prompt. The deploytool GUI opens.
Copying the Example Files
Prepare to run the example by copying needed files into your work area as follows:
1.
Navigate to matlabroot\toolbox\dotnetbuilder\Examples\VS8\NET\MagicSquareExample.
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.
3.
Rename the subfolder MagicSquareExample to magic_square. The example files should now reside in D:\dotnetbuilder_examples\magic_square.
4.
Using a system command prompt, navigate to D:\dotnetbuilder_examples\magic_square by switching to the D: drive and entering cd \dotnetbuilder_examples\magic_square.
Testing the M-File You Want to Deploy
In this example, you test a precreated M-file (magicsquare.m) containing the predefined MATLAB function magic, in order to have a baseline to compare to the results of the function when it is finally wrappered as a deployable .NET component.
1.
Using MATLAB, locate the magicsquare.m file at D:\dotnetbuilder_examples\magic_square\MagicDemoComp. The contents of the file are as follows:
function y = makesquare(x)
%MAKESQUARE Magic square of 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.
To run makesquare, ensure that MATLAB can find it. Select File > Set Path in MATLAB to add the D:\dotnetbuilder_examples\magic_square\MagicDemoComp folder to the MATLAB search path.
3.
At the MATLAB command prompt, enter makesquare(5) and view the results. The output should appear as follows:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
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,...,varargin)
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.
When the MATLAB Builder NE product processes your M-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 MATLAB 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 M-code discussed in Testing the M-File You Want to Deploy.
Use the following information when creating your component as you work through this example:
Project Name magicSquareComp
Class Name magicSquareClass
File to compile makesquare.m
1.
Create a deployment project. A project is a collection of files you bundle together under a project file name (.prj file) for your convenience in the Deployment Tool. Using a project makes it easy for you to build and run an application many times—effectively testing it—until it is ready for deployment.
1.
Type the name of your project in the Name field.
2.
Enter the location of the project in the Location field. Alternately, navigate to the location.
3.
Select the target for the deployment project from the Target drop-down menu.
4.
Click OK.
2.
On the Build tab, add what you want to compile, and any supporting files, to the project.
1.
Do the following, depending on the type of application you are building:
*
If you are building a COM application or Microsoft® Excel® add-in, click Add files.
*
If you are building a .NET application, click Add class. Type the name of the class in the Class Name field, designated by the letter "c":
For this class, add files you want to compile by clicking Add files. To add another class, click Add class.
2.
Add any supporting files. For example, you can add the following files, as appropriate for your project:
*
Functions called using eval (or variants of eval)
*
Functions not on the MATLAB path
*
Code you want to remain private
*
Code from other programs that you want to compile and link into the main file
If you want to include additional files, in the Shared Resources and Helper Files area, click Add files/directories. Click Open to select the file or files.
3.
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
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 functions you add to the project at design time.
2.
Compiles the C# code and generates /distrib and /src subfolders
The second step of the build process compiles 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
Subfolder Files Description
src ComponentName
_mcc_component_data.cs C# component data file
ClassName1.cs ...
ClassNameN.cs C# wrapper class file
distrib ComponentName.dll .NET component assembly
ComponentName.pdb .NET component debug file (Debug builds only)
ComponentName.xml .NET component XML documentation file
MWArray.xml
component_name.xml
component_name_overview.html Documentation template files. See Using Enhanced XML Documentation Files.
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.
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 must 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.
After packaging, the package resides in the distrib subfolder. On Windows, the package is a self-extracting executable. On platforms other than Windows, it is a .zip file. Verify that the contents of the distrib folder contains the files you specified.
What Happens in the Packaging Process?. The package process zips the following files into a single self-extracting executable, componentName.exe:
*
componentName.dll
*
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 is reused and shared among all subsequent class instances within the component, resulting in more efficient 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 M-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 myclass are instantiated in an application, only one MCR is initialized, and it is shared by all instances of myclass.
mcc -B 'dotnet:mycomponent,myclass,2.0,Private,local' foo.m bar.m
Copying the Package You Created
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.
Back to Top of Page Back to Top
Using the Command Line to Create .NET Components
Instead of using the Deployment Tool to create .NET components, you can use the mcc command.
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 mcc command and all of its options, see the MATLAB 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.
mcc - W 'dotnet:component_name,class_name, 0.0|2.0, Private|Encryption_Key_Path,local|remote' file1 [file2...fileN][class{class_name:file1 [,file2,...,fileN]},... [-d output_dir_path] -T link:lib
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 .NET Bundle Files to Simplify the Command
To simplify the command line used to create .NET components, you can use the .NET Builder bundle file, named dotnet, to make creating .NET components easier. When using this bundle file, you must still pass in the four parts of the -W argument text string, however, you do not have to specify the -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 predefined .NET Builder bundle file.
mcc -B 'dotnet:mycomponent,myclass,2.0,encryption_keyfile_path,local'
foo.m bar.m
In this example, the builder uses the .NET Framework version 2.0 to compile the component into a shared assembly using the key file specified in encryption_keyfile_path to sign the shared component.
Example: Creating a .NET Component Namespace
The following example creates a .NET component from two M-files foo.m and bar.m.
mcc - B 'dotnet:mycompany.mygroup.mycomponent,myclass,0.0,Private,local'
foo.m bar.m
The example creates a .NET component named mycomponent that has the following namespace: mycompany.mygroup. The component contains a single .NET class, myclass, which contains methods foo and bar.
To use myclass, place the following statement in your code:
using mycompany.mygroup;
Example: Adding Multiple Classes to a Component
The following example creates a .NET component that includes more than one class. This example uses the optional class{...} argument to the mcc command.
mcc - B 'dotnet:mycompany.mycomponent,myclass,2.0,Private,local' foo.m bar.m
class{myclass2:foo2.m,bar2.m}
The example creates a .NET component named mycomponent with two classes:
*
myclass has methods foo and bar
*
myclass2 has methods foo2 and bar2
Back to Top of Page Back to Top
Magic Square Example: .NET Programmer Tasks
The following tasks are usually performed by the .NET programmer.
Key Tasks for the .NET Programmer
Task Reference
1. Ensure you have the needed files from the MATLAB programmer before proceeding. Gathering Files Needed for Deployment
2. Use the component in a .NET application. Compile and run the component to ensure it produces the same results as your M-code. Using the Component in an Application
3. Archive and distribute the output to end users. Distributing the Component to End Users
4. Integrate classes generated by the MATLAB Builder NE product into existing .NET applications. Integrating .NET Classes Generated by MATLAB into a .NET Application
5. Verify your .NET application works as expected in your end user's deployment environment. Building and Testing the .NET Application
Gathering Files Needed for Deployment
Before beginning, verify you have access to the following files, created by the MATLAB programmer in Copying the Package You Created. The following files are required to deploy to users who do not have a copy of MATLAB installed:
*
MCR Installer. For locations of all MCR Installers, run the mcrinstaller command.
*
readme.txt
See Packaging Your Component (Optional) for more information about these files. You will also want to communicate the location of the MWArray Class Library Reference. You can also browse to this library from the MATLAB Builder NE help tree (left pane of MATLAB Product Help).
How Component Deployment Works. To deploy the component, run the MCR installer. The installer does the following:
1.
Installs the MCR (if not already installed on the target machine)
2.
Installs the component assembly in the folder from which the installer is run
3.
Copies the MWArray assembly to the Global Assembly Cache (GAC), as part of installing the MCR
Note Since installing the MCR requires write access to the system registry, you must have administrator privileges to run the MCR Installer.
Note On target machines where the MCR Installer is run, the MCR Installer puts the MWArray assembly in installation_folder\toolbox\dotnetbuilder\runtime\architecture
\version_number.
The MCR Installer uses a standard Microsoft installation file that provides the following features:
*
Integrates with Add/Remove Programs in the Control Panel
*
Checks software prerequisites before installation
*
Checks for proper user permissions
*
Rolls back the system to its prior state on installation failure
*
Supports component versioning
Using the Component in an Application
1.
Write source code for an application that uses the .NET component created in Building Your Component.
The C# source code for the sample application for this example is in MagicSquareExample\MagicSquareCSApp\MagicSquareApp.cs.
The program listing is shown here.
Tip Although MATLAB Builder NE generates C# code for the MagicSquare 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 Sample Applications (Microsoft Visual Basic .NET).
MagicSquareApp.cs
// *******************************************************************************
//
// MagicDemoApp.cs
//
// This file is an example application for the MATLAB Builder NE product.
//
// Copyright 2001-2009 The MathWorks, Inc.
//
// *******************************************************************************
using System;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using MagicDemoComp;
namespace MathWorks.Demo.MagicSquareApp
{
///
/// The MagicSquareApp demo class computes a magic square of the user-specified size.
///
///
/// args[0] - a positive integer representing the array size.
///
class MagicDemoApp
{
#region MAIN
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
MWNumericArray arraySize= null;
MWNumericArray magicSquare= null;
try
{
// Get user-specified command line arguments or set default
arraySize= (0 != args.Length) ? System.Double.Parse(args[0]) : 4;
// Create the magic square object
MagicSquare magic= new MagicSquare();
// Compute the magic square and print the result
magicSquare= (MWNumericArray)magic.makesquare((MWArray)arraySize);
Console.WriteLine("Magic square of order {0}\n\n{1}", arraySize, magicSquare);
// Convert the magic square array to a two-dimensional native double array
double[,] nativeArray= (double[,])magicSquare.ToArray(MWArrayComponent.Real);
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++)
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);
}
}
#endregion
}
}
2.
Build the application using Visual Studio® .NET.
Note In the project file for this example, the MWArray assembly and the magic square component 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.
1.
Open the project file for the Magic Square example (MagicSquareCSApp.csproj) in Visual Studio .NET.
2.
If necessary, add a reference to the MWArray component in matlabroot\toolbox\dotnetbuilder\bin\
architecture\framework_version.
3.
If necessary, add a reference to the Magic Square component (MagicSquareComp), which is in the distrib subfolder.
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 .zip file bundled with WinZip, unzip and extract the contents to the development machine.
Integrating .NET Classes Generated by MATLAB into a .NET Application
*
Classes and Methods
*
Component and Class Naming Conventions
*
Versioning
*
Managing Data Conversion Issues with MATLAB Builder NE Data Conversion Classes
*
Automatic Casting to MATLAB Types
*
Adding Fields to Data Structures and Data Structure Arrays
*
About MATLAB Array Indexing
*
Accessing Your Component On Another Computer
Classes and Methods. The 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.
Component and Class Naming Conventions. Typically you should specify names for components and classes that will be clear to programmers who use your components. For 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 name 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 as the underscore (_) character.
Versioning. 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 MWArray. To pass parameters, you can either instantiate one of the MWArray subclasses explicitly, or, in many cases, pass the 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 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: MWNumericArray, MWLogicalArray, MWCharArray, MWCellArray, and MWStructArray.
MWArray and its derived classes provide the following functionality:
*
Constructors and destructors to instantiate and dispose of MATLAB 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.
Automatic Casting to MATLAB Types.
Note Because the conversion process is automatic (in most 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 array of these types to an appropriate MWArray type.
Note This conversion is transparent in C# applications, but might require an explicit casting 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, is of the .NET native type System.Double. The builder casts this argument to a MATLAB 1-by-1 double MWNumericArray type (which is a wrapper class containing a MATLAB double array).
See Data Conversion Rules 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, and MWNumericArray, respectively.
Adding Fields to Data Structures and Data Structure Arrays. When adding fields to data structures and data structure arrays, do 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 Sample Applications (C#) and 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.
Don't keep the array in MATLAB type; convert it to a native array first. See 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.
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.
You must also add a reference to the MWArray component in matlabroot\toolbox\dotnetbuilder\bin\architecture\framework_version.
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.
没有评论:
发表评论