Code covered by the BSD License  

Highlights from
Integrating MATLAB with C#

4.44444

4.4 | 39 ratings Rate this file 272 Downloads (last 30 days) File Size: 1.56 MB File ID: #12987
image thumbnail

Integrating MATLAB with C#

by

 

13 Nov 2006 (Updated )

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 (R2009b)
Other requirements Microsoft Visual Studio
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (73)
18 Feb 2014 Heather

Hi, did anyone find a solution to the exception raised when using mode 2, i.e. "The type initializer for 'dotnet.dotnetclass' threw an exception."
TIA

12 Feb 2014 Changyu

Re: mclmcrrt711.dll is not there, I modified the VC code, replacing mclmcrrt711.dll with mclmcrrt8_2.dll because I use MATLAB 2013b which is upgraded to mclmcrrt8_2.dll. The code works well right now ;)

11 Feb 2014 Chris

Check your "Path" environment variable in windows to see if the directory with the mclmcrrt711.dll is in it (usually in c:\program files\matlab\rxxxxx\runtime\win64 or \win32) otherwise you will either need to edit your path variable or add it in your program to search for the dll's location

11 Feb 2014 Changyu

I don't have a MATLAB Builder NE, I try to use MATLAB Compiler to run the MATLAB code with C shared Lib, but get this error while running the C# program: "Unable to load DLL 'mclmcrrt711.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)" Do someone know how to solve this? I have checked my MCR version, It looks compatible with my MATLAB.

10 Dec 2013 Alex Gerard  
13 Aug 2013 Vishnu  
13 Aug 2013 Vishnu  
28 Feb 2013 Pranava

I have to run a matlab file through a C#(XNA game) interface. My matlab file is in turn using a dll library as it is fetching real time data from a hardware device. The matlab file does some filtering and then outputs an integer. Can I use .NET assembly method mentioned here for my matlab file?? Any suggestions on which method is best for this file?

07 Feb 2013 Hongbiao Yang

This post is really helpful. But still there are some hard code that is not satisfactory. The command
eval(['mcc -N -d ' dnetdir ' -W ''dotnet:dotnet,'
In this command, the parameter after the -W, which is 'dotnet:dotnet', is comprised of both a constant and a variable. The first one should always be 'dotnet', while the second one should be identical with the name of the dll, which is exactly the case in this example. When I change the dll name to some more meaningful name in my project, it reports the error... The work around is to just change the second 'dotnet' into whatever your dll name is. Hope this helps for some people. LOL

23 Nov 2012 Miguel  
02 Nov 2012 Ronan CIMADURE  
24 Oct 2012 Bahareh

Thanks David, it is a great tutorial,thank you so much. I like to know which solution is faster? I have a function file in matlab and I created .Net assembly of it and used it in C# but it worked very slow there.

15 Sep 2012 Vladimir

I have same problem with mode = 2.
its threw exception when try to compile:
"The type initializer for 'dotnet.dotnetclass' threw an exception."
work on visual studio2010,matlab 2011a x64. Previous problem : "Could not load file or assembly 'MWArray, Version=2.9.1.0, Culture=neutral..." was successfully fixed like there: http://www.mathworks.com/support/solutions/en/data/1-B0JOFC/index.html?solution=1-B0JOFC

20 Jul 2012 Zhenhua Dai

Very helpful!
Thanks!

26 Jun 2012 TENT  
26 Mar 2012 Kavitha

I could accomplish connection between C# and matlab through "deploytoool" in matlab. we have to build .dll file using that in matlab and can call it from C#

20 Mar 2012 Shehroze Malik

I am having the same issue.
It says cannot find dontnet , are you missing a refrence.
I add the dll and and it shows up in the object browser , but when i try o compile it , it is automatically removed from the rowser , though it is showing up in the solution , any1 having any idea why this is hppening

19 Mar 2012 ondrej

hi
I gave it another shot and ALL 3 types of integration work!

I used Matlab 2012a 64bit, VS2010. I explicitly set during the matlab assembly deployment to use 4.0 .net i.e.:

eval(['mcc -N -d ' dnetdir ' -W ''dotnet:dotnet,' ...
'dotnetclass,4.0,private'' -T link:lib ' mfile]);

thanks for this great tutorial, David!

19 Mar 2012 ondrej

not working with 64bit matlab

15 Mar 2012 Adriano

hello everybody, i'm trying to run this example with Matlab R2008B and visual studio 2010 professional. One moment, the application stops and ask me to choose the compiler but does not propose any. Must I install a compiler first?
* I will give my stars later

14 Mar 2012 rencs

I debug the demo in the WIN7 flagship system,there is normal except error dialog box-Microsoft Visual C++ Runtime Library,"Runtime Error".I doubt that the problem is system

07 Mar 2012 Kavitha

I am using Matlab 2010b and visual C# 2010 express. I could run the the build_mcode.m to generate .dll files. But when I start running C#, it shows dotnet is "Error 1 The type or namespace name 'dotnet' could not be found (are you missing a using directive or an assembly reference?) D:\KAVITHA\Kavitha_Workspace\GameProgrammingC#\CSharp_MATLAB\VSProj\Program.cs 12 7 CSharp_MATLAB"
Could any one please help me?

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?

19 Nov 2011 Morris

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

19 Nov 2011 Morris  
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.

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

14 Sep 2011 nejc

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

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 Jul 2011 Nitin  
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

26 May 2011 Mhaw Sayar  
18 May 2011 mohamed yehia  
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 :)

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

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 ';']);

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.

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!

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

09 Feb 2011 Developix  
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

20 Sep 2010 Aleksandra  
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

09 Jul 2010 Abd El Kareem El Namouly  
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.

23 May 2010 Husnin Mubarak

Thanks. The great !

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.

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.

25 Jan 2010 Kumar Devvrat

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

09 Nov 2009 Petter

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

Thanks
Petter

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

16 Apr 2009 minibela

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

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.

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?

09 Jan 2009 Fajri Kurniawan

you can try this:

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

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?

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?

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 Jul 2008 Rebecca Gao

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

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.

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.

16 Apr 2008 hailu sergota  
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 .

27 Mar 2008 wang lailing

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

17 Mar 2008 Kostas Ramantas  
02 Dec 2007 elif acar

Thank u so much
2. solution is very well

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.

23 Oct 2007 Speed Yang

These mix programming demo are very valued.

01 Jul 2007 nahid taherian  
05 Apr 2007 B. Roossien

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

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.

23 Feb 2007 André Koscianski

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

21 Dec 2006 Abnc tyu  
Updates
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.

Contact us