Home > Uncategorized > COM interoperability with Matlab 7 in C#

COM interoperability with Matlab 7 in C#

If you try to import Matlab 7.0’s com object into C#, you get this error when you try to call it using early binding.

MLApp.MLAppClass MyMatlab = new MLApp.MLAppClass();
textBox1.Text = MyMatlab.Execute("version");

results in:

An unhandled exception of type ‘System.InvalidCastException’ occurred
in Test version7.exe
 
Additional information: QueryInterface for interface MLApp.DIMLApp
failed. 
 
This is apparently due to a mix up with GUID’s for mlapp.tlb, so, instead of hacking with the registry to correct their GUID, you can alternatively use late binding on the object thus;

Type objFactoryType;
   objFactoryType = Type.GetTypeFromProgID("Matlab.Application");
   object objFactory;
   objFactory = Activator.CreateInstance(objFactoryType);
   object[] args = new object[1];
   args[0]="version";
   object retval;
   retval = objFactoryType.InvokeMember("Execute",BindingFlags.InvokeMethod,null,
           objFactory,args);
   MessageBox.Show(retval.ToString());

Which works fine…

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: