2

We have an application that is a C/C++/MFC desktop application, with some C++/CLI assemblies that allow us to access some managed code functionality. The app is crashing at startup in release mode only with the message

An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module. Additional information: The type initializer for '' threw an exception.

How can I go about debugging this scenario and what are the issues in mixing managed/unmanaged code? What special steps do I have to take to make them play nicely?

  • 3
    Go to Debug->Exceptions and check "Thrown" for Common Language Runtime Exceptions. – Matt Smith Jan 10 '12 at 19:41
  • Also, when attached with the debugger make sure you are using mixed mode debugging (both Native and Managed). If you are launching from the debugger the setting is in Project Properties->Configuration Properties->Debugging->Debugger Type. If you are attaching, there is an "Attach to" with a "Select" button where you can specify. BTW, are you using .NET 4 or .NET 2? – Matt Smith Jan 10 '12 at 19:46
  • The problem is that this issue only manifests itself in release mode –  Jan 10 '12 at 21:01
  • You can still debug with release mode. Or are you saying that it only manifests itself when you are not attached with a debugger? – Matt Smith Jan 10 '12 at 21:07

2 Answers2

0

Things to suspect are:

Missing unmanaged DLLs. You can use Depends (from Sysinternals) and start profiling, but I've struggled to get good results in mixed-mode.

Make a native minimal test harness which has the same dependencies, and run that through Depends - you will get definitive information about missing DLLs.

Are you using obfuscation in your release build product? The obfuscation software we use adds a field to types in evaluation mode. We have fixed offset structs, yet the new field doesn't get an explicit offset. This is an error which would be flagged up at compile time if it was in our own code. Since the obfuscator is dynamically patching the assembly, the CLR has no option but to fail to load the invalid type at runtime.

Rob
  • 4,210
  • 3
  • 30
  • 25
0

In my opinion (based on some trouble I have had) Matt Smith's comment is the most useful answer; actually, check 'Thrown' for all types of exception. Quite often the problem is a crash in the constructor of a global object. See also answer 5 at

http://www.codeproject.com/Questions/67419/The-type-initializer-for-threw-an-exception

which says (among other things):

Click Debug--> Exceptions and check ON all the Thrown checkboxes. This will cause the debugger to stop on all first chance exceptions and will help you find the error under the Type Initializer error that you're seeing. If it is related to another assembly, as mine was, you can use Microsoft's Assembly Binding Log Viewer tool to help determine the problem.

Graham Asher
  • 1,648
  • 1
  • 24
  • 34