Skip to Main Content Skip to Search
Product Documentation

Type-Safe Interface Generation and Implementation

Type-Safe Interfaces: An Alternative to Manual Data Marshaling

.NET Developer

RoleKnowledge BaseResponsibilities

.NET Developer
  • Little to no MATLAB experience

  • Moderate IT experience

  • .NET expert

  • Minimal access to IT systems

  • Integrates deployed component with the rest of the .NET application

MATLAB's data types are incompatible with native .NET types.

To send data between your application and .NET, you perform these tasks:

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

  2. 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:

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

Advantages of Implementing a Type-Safe Interface

Some of the reasons to implement type-safe interfaces include:

How Type-Safe Interfaces Work

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

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.

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.

  1. Write and Test Your MATLAB Code

  2. Develop Your Interface Using Native .NET Types

  3. Build Your Component and Generate Your Type-Safe API

  4. Develop a Main Program Using Your Interface

  5. Compile the Main Program

  6. Run the Main Program

Write and Test Your MATLAB Code

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

Develop Your Interface Using Native .NET Types

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

 Specifying Outputs

 Independent Ordering of Input and Output Parameters

Compile IAddOne into an Assembly.  Compile IAddOne.cs into an assembly using Microsoft Visual Studio.

Build Your Component and Generate Your Type-Safe API

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.

  1. 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 NameAddOneComp
    Class NameMechanism
    File to compileaddOne

      Note   Do not click the Build button at this time.

  2. Click the Actions ( ) button.

  3. Select Settings.

  4. On the Type-Safe API tab, do the following:

    1. Select Enable Type-Safe API.

    2. In the Interface assembly field, specify the location of the type-safe/WCF interface assembly that you built.

    3. Select IAddOne from the .NET interface drop-down box. The interface name is usually prefixed by an I.

        Tip   If the drop-down is blank, the Deployment Tool may have been unable to find any .NET interfaces in the assembly you selected. Select another assembly.

    4. Specify Mechanism, as the class name you want the generated API to wrap, in the Wrapped Class field.

    5. Click Close to dismiss the Settings dialog box.

      Note   Leave the Namespace field blank.

  5. 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:

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

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

        Tip   If the assembly containing the .NET interface IAddOne is not in the current folder, specify the full path.

      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.

Develop a Main Program Using Your Interface

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:

 Where To Find Example Code

 AddMaster.cs Program

Compile the Main Program

Compile the main program using Microsoft Visual Studio by doing the following:

  1. Create a Microsoft Visual Studio project named AddMaster.

  2. Add references in the project to the following files:

    This Reference...Defines...
    IAddOne.dllThe .NET native type interface IAddOne
    MechanismIAddOne.dllThe generated type-safe API
    AddOneCompNative.dllThe MATLAB Builder NE component

      Note   Unlike other .NET deployment scenarios, you do not need to reference MWArray.dll in the server program source code. The MWArray data types are hidden behind the type-safe API in MechanismIAddOne.

  3. Compile the program with Microsoft Visual Studio.

Run the Main Program

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
  


Recommended Products

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