| Contents | Index |
| On this page… |
|---|
Type-Safe Interfaces: An Alternative to Manual Data Marshaling |
.NET Developer
| Role | Knowledge Base | Responsibilities |
|---|---|---|
|
|
|
|
MATLAB's data types are incompatible with native .NET types.
To send data between your application and .NET, you perform these tasks:
Marshal data from .NET input data to a deployed function by creating an MWArray object from native .NET data. The public functions in a deployed component return MWArray objects.
Marshal the output MATLAB data in an MWArray into native .NET data by calling one of the MWArray marshaling methods (ToArray(), for example).
Manual Data Marshaling Without a Type-Safe Interface

As you can see, manually marshaling data adds complexity and potential failure points to the task of integrating deployed components into a .NET application. This is particularly true for these reasons:
Your application cannot detect type mismatch errors until run-time. For example, you might accidentally create an MWArray from a string and pass the array to a deployed function that expects a number. Because the wrapper code generated by MATLAB Builder NE expects an MWArray, the .NET compiler is unable to detect this error and the deployed function either throws an exception or returns the wrong answer.
Your end users must learn how to use the MWArray data type or alternately mask the MWArray data type behind a manually written (and manually maintained) API. This introduces unwanted training time and places resource demands on a potentially overcommitted staff.
You can avoid performing tedious MWArray data marshaling by using type-safe interfaces. Such interfaces minimize explicit type conversions by hiding the MWArray type from the calling application. Using type-safe interfaces allows .NET Developers to work directly with familiar native data types.
Simplified Data Marshaling With a Type-Safe Interface

Some of the reasons to implement type-safe interfaces include:
You avoid training and coding costs associated with teaching end users to work with MWArrays.
You minimize cost of data you must marshal by either placing MWArray objects in type-safe interfaces or by calling MWArray-based functions in the deployed component.
Flexibility — you mix type-safe interfaces with manual data marshaling to accommodate data of varying sizes and access patterns. For example, you may have a few large data objects (images, for example) that would incur excess cost to your organization if managed with a type-safe interface. By mixing type-safe interfaces and manual marshaling, smaller data types can be managed automatically with the type-safe interface and your large data can be managed on an as-needed basis.
Every MATLAB Builder NE component exports one or more public methods that accept and return data using MWArrays.
Adding a type-safe interface to a MATLAB Builder NE component creates another set of methods (with the same names) that accept and return native .NET types.
The figure Architecture of a Deployed Component with a Type-Safe Interface illustrates the data paths between the .NET host application and the deployed MATLAB function.
Architecture of a Deployed Component with a Type-Safe Interface

The MATLAB function addOne returns its input plus one.
Deploying addOne with a type-safe interface creates two .NET addOne methods: one that accepts and returns .NET doubles, and one that accepts are returns MWArray. See MATLAB documentation for matching rules.
You may create multiple type-safe interface methods for a single MATLAB function. Type-safe interface methods follow the standard .NET methods for overloading.
Notice that the type-safe methods co-exist with (and do not replace) the MWArray-based methods. Your .NET application may mix and match calls to either type of method, as appropriate.
You may find MWArray methods more efficient when passing large data values in loops to one or more deployed functions. In such cases, creating an MWArray object allows you to marshal the data only once whereas the type-safe interface marshals inputs on every call.
Implementing a type-safe interface usually requires the expertise of a .NET Developer (see description of .NET Developer) because it requires performing a number of medium-to-advanced programming tasks.
Tip Data objects that merely pass through either the target or MATLAB environments may not need to be marshaled, particularly if they do not cross a process boundary. Because marshaling is costly, only marshal on demand. |
To implement a type-safe interface, follow this general workflow. Depending on whether you are primarily a MATLAB programmer or .NET developer, you may prefer to perform Steps 1 and 2 in reverse order.
Create your MATLAB program and then test the code before implementing a type-safe interface. The functions in your MATLAB program must match the declarations in your native .NET interface.
In the following example, the deployable MATLAB code contains one exported function, addOne. The addOne function adds the value one (1) to the input received. The input must be numeric, either a scalar or a matrix of single or multiple dimensions.
function y = addOne(x)
% ADDONE Add one to numeric input. Input must be numeric.
if ~isnumeric(x)
error('Input must be numeric. Input was %s.', class(x));
end
y = x + 1;
end
Note addOne must perform run-time type checking to ensure valid input. |
After you write and test your MATLAB code, develop a .NET interface that supports the native types through the API in either C# or Visual Basic . In this example, the interface, IAddOne, is written in C#.
Define IAddOne Methods. Each method in the interface must exactly match a deployed MATLAB function.
The IAddOne interface specifies six overload of addOne:
using System.ServiceModel;
[ServiceContract]
public interface IAddOne
{
[OperationContract(Name = "addOne_1")]
int addOne(int x);
[OperationContract(Name = "addOne_2")]
void addOne(ref int y, int x);
[OperationContract(Name = "addOne_3")]
void addOne(int x, ref int y);
[OperationContract(Name = "addOne_4")]
System.Double addOne(System.Double x);
[OperationContract(Name = "addOne_5")]
System.Double[] addOne(System.Double[] x);
[OperationContract(Name = "addOne_6")]
System.Double[][] addOne(System.Double[][] x);
}
As you can see, all methods have one input and one output (to match the MATLAB addOne function), though the type and position of these parameters varies.
The following code snippets provide samples of how to work with your function and the overloads in the context of the interface.
Data Conversion Rules for Using the Type-Safe Interface
Independent Ordering of Input and Output Parameters
Compile IAddOne into an Assembly. Compile IAddOne.cs into an assembly using Microsoft Visual Studio.
Note This example assumes your assembly contains only IAddOne. Realistically, it is more likely that IAddOne will already be part of a compiled assembly. The assembly may be complete even before the MATLAB function is written. |
Use either the Deployment Tool (deploytool) or the deployment command line tools to generate the type-safe API.
Using the Deployment Tool. The Deployment Tool generates the type-safe API, when you build your component, if the correct options are selected in the Settings dialog box.
Create your Deployment Tool project. Follow the steps in Deployable Component Creation in the Getting Started chapter of this user's guide.
When defining your project, use these values:
| Project Name | AddOneComp |
| Class Name | Mechanism |
| File to compile | addOne |
Click the Actions (
) button.
Select Settings.
On the Type-Safe API tab, do the following:
Select Enable Type-Safe API.
In the Interface assembly field, specify the location of the type-safe/WCF interface assembly that you built.
Select IAddOne from the .NET interface drop-down box. The interface name is usually prefixed by an I.
Specify Mechanism, as the class name you want the generated API to wrap, in the Wrapped Class field.
Click Close to dismiss the Settings dialog box.
Build the project as usual by clicking the Build
button.
Using the Deployment Command-Line Tools. To generate the type-safe API with your component build (compilation) using mcc, do the following:
Build the component by entering this command from MATLAB:
mcc -v -B 'dotnet:AddOneComp,Mechanism,3.5,private,local'
addOne
See the mcc reference page in this user's guide for details on the options specified.
Generate the type-safe API by entering this command from MATLAB:
ntswrap -c AddOneComp.Mechanism -i IAddOne -a IAddOne.dll
where:
-c specifies the namespace-qualified name of the MATLAB Builder NE component to wrap with a type-safe API. If the component is scoped to a namespace, specify the full namespace-qualified name (AddOneComp.Mechanism in the example). Because no namespace is specified by ntswrap, the type-safe interface class appears in the global namespace.
-i specifies the name of the .NET interface that defines the type-safe API. The interface name is usually prefixed by an I.
-a specifies the absolute or relative path to the assembly containing the .NET statically-typed interface, referenced by the -i switch.
Caution Not all arguments are compatible with each other. See the ntswrap reference page in this user's guide for details on all command options. |
You have now built your component and generated a type-safe API to work with it. Next, you need to develop a main program (AddMaster.cs) that calls all the overloads of addOne defined by the IAddOne interface you developed earlier:
Compile the main program using Microsoft Visual Studio by doing the following:
Create a Microsoft Visual Studio project named AddMaster.
Add references in the project to the following files:
| This Reference... | Defines... |
|---|---|
| IAddOne.dll | The .NET native type interface IAddOne |
| MechanismIAddOne.dll | The generated type-safe API |
| AddOneCompNative.dll | The MATLAB Builder NE component |
Compile the program with Microsoft Visual Studio.
Run the main program from a command line.
The output should look similar to the following.
addOne(1) = 2 addOne(16) = 17 addOne(2) = 3 addOne(495) = 496 addOne([30 60 88]) = [31 61 89] addOne([0 2; 3 1]) = [1 3; 4 2] No Exceptions
![]() | Type-Safe Interfaces, WCF, and MEF | Windows Communications Foundation (WCF)™-Based Components | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |