Code covered by the BSD License  

Highlights from
Integrating MATLAB with C#

4.48

4.5 | 25 ratings Rate this file 285 Downloads (last 30 days) File Size: 1.56 MB File ID: #12987
image thumbnail

Integrating MATLAB with C#

by David Forstot

 

13 Nov 2006 (Updated 09 Feb 2010)

Three methods of integrating MATLAB code into a C# project.

| Watch this File

File Information
Description

This demo shows three ways to integrate MATLAB code into a C# project. All three methods use the same example from MATLAB, but each interacts with it in a different fashion.

The first method shows how to use the MATLAB as an automation server from C# using the engine interface via com automation. This allows you to simultaneously debug your C# application from both the C# side and the MATLAB side, using debuggers on each side.

The second method uses MATLAB Builder for .NET to create a .NET assembly. This assembly exposes the MATLAB example as a method of a class included in the component. This method can be used directly in C#. It provides intellisense, automatic data marshalling and garbage collection. This .NET assembly can be deployed royalty-free to machines that do not have MATLAB.

The third method uses MATLAB Compiler to create a C shared library ? unmanaged code. This library exposes the MATLAB example ? but not in a manner that can be used directly in .NET. Instead a wrapper class was created to provide entry into the method included the library, and to marshal the data from the managed framework into the unmanaged library. This C Shared library can also be deployed royalty-free to machines that do not have MATLAB.

It should be noted that third example is very fragile. It is not the recommended method of C# and MATLAB integration. It has only been provided to emphasize the additional work which becomes necessary to integrate C# with MATLAB when you do not use Builder for .NET. This is not a general solution to integrating a MATLAB produced C shared library with .NET but a single purpose solution designed only to work for this example. Upon further inspection it should be clear that the lack of typing when moving from managed to unmanaged code dramatically increases the risk of data handling errors. The lack of intellisense, automatic data marshalling, and garbage collection are additional detractors from this method.

Required Products MATLAB Builder NE
MATLAB Compiler
MATLAB release MATLAB 7.9 (2009b)
Other requirements Microsoft Visual Studio
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (51)
21 Dec 2006 Abnc tyu  
23 Feb 2007 André Koscianski

Have a look at this article, dated from 2003: http://www.codeproject.com/dotnet/matlabeng.asp

03 Apr 2007 Sanjaya Perera

I will develop a system using matlab and c#. So i need to integrate matlab with c#. I hope this software can be used to perform that.

05 Apr 2007 B. Roossien

Well commented and documented example of different ways to incorporate Matlab in C#.

01 Jul 2007 nahid taherian  
23 Oct 2007 Speed Yang

These mix programming demo are very valued.

07 Nov 2007 srinivas sharma

It is a very useful information. I dont have the count of stars , to rate this. I swear and vouch for my comment truely.

02 Dec 2007 elif acar

Thank u so much
2. solution is very well

17 Mar 2008 Kostas Ramantas  
27 Mar 2008 wang lailing

very good.I think it will be much better,if you give us some examples.

09 Apr 2008 ismail aqil

great !!
But Do YOu think the performance of the written code in matlab and integrated with .Net Framework is well as it was written entirely in c# ???

thank you in advance .

16 Apr 2008 hailu sergota  
05 May 2008 Hayri Simsek

When I try to run your program I get an error saying
"The type initializer for 'dotnet.dotnetclass' threw an exception."

I am using MATLAB 2006b ..
What can I do.

30 Jun 2008 Hayri Simsek

You can use deploytool, also
On command window
type deploytool
A GUI will be opened and it will be very easy for you to copile your project.

01 Jul 2008 Rebecca Gao

Is it possible to call library which is built in .net, from matlab environment?

09 Aug 2008 Matteo Sorci

problem with Visual Studio 2008.
When trying to add the reference to the mlapp.tlb I have an error, the reference can not be added. Any solutions?

01 Oct 2008 Veroljub Zmijanac

Very nice work.
I am using Matlab COM integration, provided by you. Great work.

Do you, maybe, if it is possible to run this kind of integration with just a Matlab Component Runtime, because I can get it to work?

28 Nov 2008 Sergii Kolomiichuk

Thank you, it's very usefull examle. But I have another problem: How i can pass Strings to my m-function from C#
I tryied to MarshalAs(UnmanagedType.LPStr) but it didn't work.
Program throws "Out of memory", what can be my problem?

09 Jan 2009 Fajri Kurniawan

you can try this:

String str = "mystring";
matlabins.mFunction( (MWArray)str );

03 Feb 2009 Colin Rodgers

thank you for adding this tutorial.
Thus far however, i've had no luck getting the initial build_mcode file to compile a .NET assembly.

Every attempt to compile the code in matlab results in the following error.
>>run build_mcode
Compiling .NET Assembly...
??? Error using ==> build_mcode at 61
Failed to successfully compile .NET assembly.

Error in ==> run at 74
evalin( 'caller' , [script ';'] );

I have thus far reinstalled my VS2008 install and updated my windows SDK instal as well, hoping it was simply an issue with one of the compilers but this has failed to solve any of the issues.
Does anybody have any suggestions on how to overcome this problem?

07 Feb 2009 Rotem Littman

Thanks for the tutorial.

I use matlab from c#, and I have a memory problem:
my code open an image file, processes it and saves it again.
When I use the code from matlab there are no problems even for very big images, but from c# it throws an "out of memory exception" on much smaller files (it does work for very small files). Could the problem be memory allocation for the MCR? If so, I do I change it? I have no problem letting matlab use the virtual memory, but how do I do it?

Thanks,
Rotem.

16 Apr 2009 minibela

Solution 2 works for me well. Very good example. Thanks a lot!

05 Jun 2009 Rangana Jayawardena

Hi....i tried to use this solution but at the very first step...(When i run the .m file)i'm getting this Error...please some one help me to overcome this ....

"Compiling .NET Assembly...
??? Error using ==> mcc
The output directory,
  'G:\ABTD'
does not exist.

Error in ==> build_mcode at 55
eval(['mcc -d ' dnetdir ' -W ''dotnet:dotnet,' ...

Error in ==> run at 57
          evalin('caller', [s ';']);"

Thanks

09 Nov 2009 Petter

Which one of these solutions would be the best in terms of execution speed?

Thanks
Petter

25 Jan 2010 Kumar Devvrat

Thanks .Helped me completely...used .Net assembly...worked for me .
Well documented 10/10

31 Mar 2010 Steven Lu

I tried to run the application with mode 3 but get the following error:
Unable to load DLL 'cshared.dll': The specified module could not be found.
However I saw the CShared.dll in the directory. I use visual studio 2008 pro.

05 Apr 2010 Steven Lu

I recompiled chared.dll to make it working, however, when I call csharedInitialize(), there is runtime error. Though I can still get the returned value, I am wondering is there anything I can do to remove the error.

23 May 2010 Husnin Mubarak

Thanks. The great !

22 Jun 2010 Gautam Dash

Thanks. I am still unable to get it to work though. mxCreateDoubleMatrix() returns a Zero IntPtr. I get a subsequent exception "ArgumentNullException: Value cannot be null. Parameter name: Destination" when I try to do a Marshal.Copy() from the double array to the IntPtr.

09 Jul 2010 Abd El Kareem El Namouly  
15 Sep 2010 Rakesh Reddy

Thanks. But for me it is throwing an exception "typeinitialization exception was unhandled". I am thinking visual studio is unable to handle MWArry.dll. Can anyone help me

20 Sep 2010 Aleksandra  
11 Nov 2010 Andrew Schuessler

This looks good but the dotnetclass doesn't seem to work, I get a 'The type initializer for 'dotnet.dotnetclass' threw an exception.' error.

Any ideas?
Thanks in advance

09 Feb 2011 Developix  
22 Feb 2011 Yeasin Hossain

thanks but getting this error

Error 1 Assembly 'dotnet, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' uses 'MWArray, Version=2.9.1.0, Culture=neutral, PublicKeyToken=e1d84a0da19db86f' which has a higher version than referenced assembly 'MWArray, Version=2.0.0.0, Culture=neutral, PublicKeyToken=e1d84a0da19db86f' c:\Documents and Settings\Administrator\Desktop\CSharp_MATLAB\Output\dotnet.dll CSharp_MATLAB

I am using Matlab 7.6, is this the reason

25 Feb 2011 Ning

It is really good tutorial.

In my matlab function, I called a "princomp" function from statistical toolbox.
I got the code working for the method 1, which requires a matlab installation.

However, i have a problem with the second method, which is the matlab installation-free approach with an error:
Undefined function or method 'princomp' for input arguments of type 'double'

Does it have anything to do with the licensing issue, anybody could help me out. Appreciate it!

02 Apr 2011 Pat

R2010b on Windows 7 Ult 64-bit with VS 2005 SP2 (and configured the project for 32-bits).

mode = 1 (UseEngine) works.

mode = 2 repeatedly fails with:

http://img148.imageshack.us/i/mwarrayfileloadexceptio.jpg/

The version of MWArray.dll that came with the project (folder Output) is 2.10.1.0 – not the 2.9.1.0 suggested by the exception dialog. I’ve looked all over my machine (including in the registry) for a MWArray.dll that’s 2.9.1.0 but without success.

I might note that there is a MWArray.dll under %matlabroot% but it too is 2.10.1.0.

04 May 2011 nur

I'm trying to this project, with R2009b and VS 2008 but in third step I have this problem
??? Error using ==> mcc
The output directory,
  'C:\Documents'
does not exist.

Error in ==> build_mcode at 53
eval(['mcc -N -d ' dnetdir ' -W ''dotnet:dotnet,' ...

Error in ==> run at 57
          evalin('caller', [s ';']);

04 May 2011 nur

I'm trying to this project, with R2009b and VS 2008 but in third step I have this problem
??? Error using ==> mcc
The output directory,
  'C:\Documents'
does not exist.
Error in ==> build_mcode at 53
eval(['mcc -N -d ' dnetdir ' -W ''dotnet:dotnet,' ...
Error in ==> run at 57
          evalin('caller', [s ';']);
Can anyone help me, its to important

09 May 2011 akrita agarwal

working perfectly fine ... if nebody has be doubt mail it to me : akrita.ag@gmail.com or post it here :)

18 May 2011 mohamed yehia  
26 May 2011 Mhaw Sayar  
17 Jun 2011 Murat Ates

For the problems related with "The output directory ... does not exist". That's due to the spaces in the file names. If you put the folder under C:\ that would not be a problem I think. "fileparts" function fails with folders with space as far as I see.

Thanks,
Murat

14 Jul 2011 Nitin  
09 Sep 2011 nejc

Hello! Your examples work perfectly. But I have a problem with different thing.I'm trying to pass bitmap image from C# to Matlab, process it there and then return it back to C#.
I tried with this example: http://www.mathworks.com/support/solutions/en/data/1-33B9S6/index.html?product=MN&solution=1-33B9S6 but the problem is always the same: "??? Undefined function or method 'imshow' for input arguments of type 'double'" I tried to pass byte array too, but no success. If anyone can help me, I would be very grateful..

14 Sep 2011 nejc

Just to let you know.. It works now, with visual studio 2010, framework v4.0 and matlab 2011..

07 Nov 2011 Thomas Younsi

Is there version of MWArray.dll and WebFiguresService.dll which can target dotNet Framework 4.0 require on Windows 7 64 bit running 32 bit application

08 Nov 2011 Thomas Younsi

Your comment is awaiting moderation.

Please release a version of MWArray which Target .NET framework 4.0. There should be a version for all .NET framework. Without this it is not posisble to run .NET 4.0 client calling into matlab generated asembly on Windows 7 64 bit (32 bit mode) simply because .NET framework 2.0 is not supported. When I target 4.0 inside matlab I expect ALL dependencies to be .NET Framework 4.0 !!! Is there a fix for the .NET builder to support Framework 4.0 for MWArray.

19 Nov 2011 Morris  
19 Nov 2011 Morris

Excuse me I'm interesting how can I convert the matlab code to C#, it's possible?

14 Dec 2011 Hal

I've imported a dll, but have run into a strange problem. I can define a class and than access it's first property, but not it's second. E.g. class.property1; will display the value of the property1, but class.property2 gives me the error Array formation and indexing are not allowed on .NET object. Any idea what the problem could be?

Please login to add a comment or rating.
Updates
03 Dec 2007

Fixed memory leak, and migrated to MATLAB R2007b.

04 Feb 2010

Updated to R2009b

09 Feb 2010

Updated for MATLAB R2009b.
Updated Readme and MATLAB functions - uses faster build options for mcc by excluding unnecessary folders on MATLAB path.

Tag Activity for this File
Tag Applied By Date/Time
external interface David Forstot 22 Oct 2008 08:48:59
c builder for net engine library assembly David Forstot 22 Oct 2008 08:48:59
integrate over airfoil yingrodge suntiwuth 24 Nov 2008 14:15:17
external interface Alexander Kluge 12 Dec 2008 05:06:36
c builder for net engine library assembly Alexander Kluge 12 Dec 2008 05:06:40
integrate over airfoil Alexander Kluge 12 Dec 2008 05:06:41
c builder for net engine library assembly C Shen 14 Jan 2009 17:13:18
c builder for net engine library assembly S 02 Feb 2010 13:58:11
c builder for net engine library assembly Krzysztof 20 Apr 2010 09:33:39
external interface Krzysztof 20 Apr 2010 09:33:43
integrate over airfoil Krzysztof 20 Apr 2010 09:33:45
c builder for net engine library assembly Rakesh Reddy 11 Sep 2010 13:30:39
c builder for net engine library assembly moussa ailane 17 Oct 2010 09:00:00
c builder for net engine library assembly Christian 02 Nov 2010 04:19:02
c builder for net engine library assembly Kundan Gupta 04 May 2011 09:31:45
c builder for net engine library assembly Aser Elshawy 04 May 2011 17:05:56
c builder for net engine library assembly Manish Kumar 09 May 2011 00:30:04
c builder for net engine library assembly Michael Huang 25 May 2011 22:35:15
external interface UNLP 26 May 2011 02:45:46
external interface Doshan 30 May 2011 13:47:14
c builder for net engine library assembly Jonah Jiang 22 Jun 2011 05:28:51
external interface Jonah Jiang 22 Jun 2011 05:28:55
integrate over airfoil Jonah Jiang 22 Jun 2011 05:28:57
c builder for net engine library assembly adabala 02 Jul 2011 11:15:29
c builder for net engine library assembly Aleksandr 12 Jul 2011 04:04:28
external interface nowaydude 29 Aug 2011 07:50:42
c builder for net engine library assembly Sudharshan V 20 Sep 2011 19:01:20
c builder for net engine library assembly Matteo Tosato 22 Sep 2011 16:30:26
integrate over airfoil Wilson Bardeskar 05 Oct 2011 22:07:50
c builder for net engine library assembly Mohsen 07 Oct 2011 15:33:44
external interface Mohsen 07 Oct 2011 15:33:49
c builder for net engine library assembly beji 13 Oct 2011 06:29:27
c builder for net engine library assembly Ladislav 02 Nov 2011 03:58:21
external interface Ladislav 02 Nov 2011 03:58:25
integrate over airfoil Gorka 11 Nov 2011 06:11:38
external interface Gorka 11 Nov 2011 06:11:43
external interface Karen Sargsyan 22 Nov 2011 09:08:19
integrate over airfoil Mathieu Caillet 05 Dec 2011 10:25:03
external interface Mathieu Caillet 05 Dec 2011 10:25:07
c builder for net engine library assembly Mathieu Caillet 05 Dec 2011 10:25:09
c builder for net engine library assembly andresnaval 07 Jan 2012 17:22:39
c builder for net engine library assembly raghunath kavuri 20 Jan 2012 07:53:48
c builder for net engine library assembly Manoela Kohler 26 Jan 2012 14:28:23
external interface Manoela Kohler 26 Jan 2012 14:28:29
integrate over airfoil Manoela Kohler 26 Jan 2012 14:28:31
c builder for net engine library assembly toan nguyen 04 Feb 2012 09:30:15

Contact us at files@mathworks.com