关于matlab与c#混合编程的问题(10)

2019-08-20 20:46

So instead, I turn to the type safe APIs generated by Builder NE (as of version 4.0, R2011a), and let Builder NE write this code for me.

Type Safe APIs

Type Safe APIs allow you to specify a kind of contract between your C# code and your MATLAB functions. You describe exactly what kind of data you want to pass back and forth between MATLAB and C#, and Builder NE generates functions for those types only. You give up a little flexiblity (you can't pass just any type of data to your MATLAB function, like you could with the MWArray-based interface), but you gain type safety. Now the C# compiler can tell if you're doing something you shouldn't be, like passing strings to a function that operates on integers. (While this often completes without error, it very seldom produces a useful result.)

In C#, the usual mechanism for establishing such a contract is an interface. An interface defines the names and input and output types of one or more functions, but provides no implemention. We can collect our

three multiply functions into the IMultiplyinterface. By convention, .NET interface names begin with a capitial I.

interface IMultiply { // Scalar multiplication double multiply(double x, double y); // Multiply vector by a scalar, return a vector double[] multiply(double[] x, double y); // Matrix multiplication double[,] multiply(double[,] x, double[,] y); } The interface uses function overloading to take advantage of the polymorphism of the MATLAB function. The functions in the C# interface have the same name as the MATLAB function; Builder NE matches interface functions to MATLAB functions by name and number of arguments. (I'll discuss the details of argument matching in a later article.) To use a type safe API, you'll need:

? ? ?

A MATLAB function

A C# interface that specifies the input and output types of that MATLAB function A C# program that calls the MATLAB function through the C# interface.

The example demonstrates how to incorporate a type safe API into a C# program. In the example, you'll work through 4 basic steps:

? Create a MATLAB function, multiply. ? Define a C# interface IMultiply.

? Compile multiply into a .NET component named Multiply and generate the type safe API MultiplyIMultiply.

? Develop a C# main program that calls multiply through the IMultiply interface.

Since we've already seen the MATLAB code and the C# interface, let's take a look at the C# main program.

Example C# Code

You invoke MATLAB functions from C# by calling the instance methods of a Builder NE-generated component. Builder NE names the type safe API class by combining the names of the MATLAB function component (Multiply) and the C# interface (IMultiply). In this case, MultiplyIMultiply is the name of the type safe API class. Call new to create an instance of the component's type safe API class: // Create an instance of the Multiply component's type safe API. IMultiply m = new Multiply.MultiplyIMultiply(); IMultiply publishes three multiply methods, one of which multiplies a vector and a scalar. Create the input data by declaring C# variables:

// Create a C# vector and a scalar. double[] v = new double[]{ 2.5, 81, 64 }; double s = 11; Finally, compute the product by calling multiply:

// Multiply the vector and the scalar. Note: all inputs and outputs // are native C# types. double[] d = m.multiply(v, s); As usual in C#, passing the wrong type of inputs (if v had been declared as a string for example) results in compile-time errors.

Building and Running the Example

Download the source code from MATLAB Central into a new directory. The download contains

the multiply MATLAB function and two Visual Studio projects. To create a runnable executable, you need to build the C# interface assembly, create adeploytool .NET assembly project for the MATLAB function and then link the main program against these two assemblies. The file ReadmeIntro.txt contains detailed instructions.

The downloaded files compile into Multiplier.exe, a C# program that calls each of the methods in the IMultiply interface and prints the results. Make sure your runtime environment is set up correctly (you need either the MCR or MATLAB'sruntime/ directory on your path) and then locate and run Multiplier.exe from a DOS command window. The output should look something like this: 17 * 3.14159 = 53.40703 [ 2.5 81 64 ] * 11 = [ 27.5 891 704 ] 8 1 6 8 1 6 91 67 67 3 5 7 * 3 5 7 = 67 91 67 4 9 2 4 9 2 67 67 91 To enable other types of multiplcation, say vector times matrix or matrix times scalar, define the appropriate methods inIMultiply and then regenerate the Multiply component.

More to Come

To keep this post from turning into a book, I've discussed only the simplest and most common uses of Builder NE's type safe APIs. Forthcoming articles will reveal the secrets of parameter ordering, address the use of structured types (cell arrays and structures), and demonstrate how type safe APIs enable interprocess communication through the Windows Communication Foundation.

In the meantime, please let me know what you think of this new feature. Will it make your job easier? How could we improve it even futher? Let us know here.

Get the MATLAB code

Published with MATLAB? 7.12

Category:

Deployment

? ? ? ? ? ? ?

Tweet

< Transferring Data Between Two Computers...

Calculating the Area Volume Under... > You can follow any comments to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

8 CommentsOldest to Newest

Alexandre Kozlov replied on June 3rd, 2011 6:23 pm UTC :1 of 8

Isn’t it possigble just to introduce a datatypes for MatLab variables? With – for backward compatibility – a generic default type (like Variant in VBA). This will help MathWorks to implement a lot of another features to resolve a lot of my problems like:

1. Auto code completion. Espetially with my own classes – I’d like to see all methods of the corresponding class after typing a variable name followed by a dot.

2. Auto doc generation. Espetially for dependency reports (today it’s impossible to know what class will be passed as a parameter for my function).

3. Methods overloading. Often I’d like to have two methods – just like in your exemple, the same name, the same parameters, but depending of their types, I want to write different function’s bodies. Today I have to write myself a function’s header to determine a case I’m in, and to call one of more specific functions (with strange names instead of the same name – as they do the same thing). 4. Etc., etc.

Joan replied on June 4th, 2011 6:02 pm UTC :2 of 8 Hi,

That sounds really interesting. Any hope to get something similar for Java? Joan

Ben Schmitt replied on June 6th, 2011 1:55 pm UTC :3 of 8

The new feature looks very useful for our applications, I look forward to reading more about it.

I also couldn’t agree more with Alexandre, it would be attractive to have the option of type-explicit m-code, equivalent to VBA’s “Option Explicit”.

Peter Webb replied on June 6th, 2011 5:10 pm UTC :4 of 8 Joan,

We’re definitely thinking about it. But I can’t say that we’ll do it, or if we do, when it might ship. :-)

Peter Webb replied on June 6th, 2011 5:15 pm UTC :5 of 8 Alexandre and Ben,

We’ve been thinking about this for at least a decade, but haven’t come up with a good design yet. It’s a real challenge balancing the ease-of-use and performance trade-offs. For now, the deployment tools are going to limit themselves to managing types at the interface between MATLAB and external execution environments like Microsoft .NET.

owr replied on June 6th, 2011 11:25 pm UTC :6 of 8

Thanks for the example – I am really enjoying the new features in Builder NE. I would love to see some good examples of using the MWObjectArray coupled with .NET External Interfaces to deploy MATLAB functions that return custom C# objects.

Peter Webb replied on June 7th, 2011 3:49 pm UTC :7 of 8

owr,

The type safe APIs will allow you to return custom C# structures from MATLAB functions. (The C# field names have to match the MATLAB field names.) Objects are trickier, because they have methods.

What exactly are you looking for? Automatic generation of a C# object that acts as a proxy for a MATLAB object? Automatic initialization of a C# object from a MATLAB structure? Or something else entirely?

Patrick replied on September 6th, 2011 10:13 am UTC :8 of 8 Loren, Peter,

Good to see that you are improving the Matlab Builder NE.

Conversion of data between Matlab and C# causes a lot of programming and maintenance overhead in our application, so I would love to use the new Type-Safe API.

I’ve tried the Type-Safe API creation to see if we could use it in our application. Some comments:

* Automatic conversion is supported for structs, not objects. Unfortunately this does not lead to a workable solution for us: Structs are not preferred in due to their limitations (eg. being sealed).

* The DeployTool can only generate one TypeSafeAPI per project. We have separated our interface with Matlab into 4 classes. It appears that for this to work we would have to split our interface into 4 seperate assemblies, and 4 TypeSafeAPI assemblies.

Because of the above reasons we will not yet use the TypeSafeAPI functionality. However, using the new Builder NE provides two good additions for us: * the method MWArray.ConvertToNativeTypes() * the MwObjectArray

In the past we have created our own data conversion utilities to maintain readability of our calls to Matlab, and create reusable wrapping code.

These utilities use reflection to map custom .Net objects to MwStructArrays. Due to the above mentioned two additions we were already able to reduce the code for our own conversion utilities by 50%! Hope to see more of these improvements in future releases!

These postings are the author's and don't necessarily represent the opinions of MathWorks.

%% Multiple Inputs and Outputs in Builder NE Type Safe APIs % Guest blogger

% returns with another in an

%


关于matlab与c#混合编程的问题(10).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:2017会计继续教育考试答案(100分通过非常全)

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: