System.Typ​eInitializ​ationExcep​tion when using a .NET library compiled with MATLAB 32-bit in C#

5 views (last 30 days)
I have compiled a .NET library using MATLAB 32-bit compiler and attempted to use it in a 32-bit C# application. When instantiating the class, I am getting a System.TypeInitializationException.
Please note the following:
  1. I have set the Configuration Manager in Visual Studio to x86 (32-bit)
  2. I am referencing MWArray.dll from the 32-bit installation of the MCR
  3. I have compiled my .NET library using the 32-bit version of MATLAB
  4. I have correctly installed the 32-bit version of the MATLAB compiler runtime
  5. I have already run gacutil.exe on the 32-bit version of MWArray.dll to register it in the GAC
  6. My machine is Windows 7 64-bit
I have called MATLAB support and have not received a solution at this time.

Accepted Answer

David Kelly
David Kelly on 4 Jun 2015
With the help of MATLAB technical support, this problem is now solved. Here's what happened:
My PC had both MATLAB 64-bit and MATLAB 32-bit versions installed. Although I was pointing to the correct 32-bit version of MWArray.dll in Visual Studio, for some reason, the 64-bit version was the one that was getting resolved.
To fix this problem, I added the 32-bit path to my Path system variable in Windows 7. This is found under Control Panel -> System -> Advanced system settings -> Advanced tab -> Environment Variables.
In the Environment Variables window, under "System variables," find the Path variable. Ensure that the 32-bit MATLAB root path is listed BEFORE the 64-bit MATLAB root path. In my case, the 32-bit path was not listed at all.
After adding the 32-bit MATLAB root path to the Windows 7 Path variable, the correct 32-bit version of MWArray.dll was now getting resolved in Visual Studio.

More Answers (1)

Guillaume
Guillaume on 4 Jun 2015
The BadImageFormatException is the real cause of the error. Do any of its property (maybe FusionLog) give any hint about why it fails to load the assembly?
All the possible cause for this exception are listed here. One possible cause is that your C# application uses a different version of the .Net framework. Which version does your matlab dll target and which version does your exe target?

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!