.NET - Capture WIN32 exceptions

  • ExceptionDll.cpp
extern "C" {
    __declspec(dllexport) void __cdecl RaiseAccessViolationException()
    {
        UINT32 *p = NULL;
        *p = 0x12345678;
    }
}

上面的C++代码将会抛出一个WIN32异常,下面我们在C#程序中调用该DLL

  • Program.cs
using System;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
 
namespace W32Ex_Catch
{
    class Program
    {
        [DllImport("ExceptionDll.dll", CharSet = CharSet.Unicode)]
        public extern static void RaiseAccessViolationException();
 
        [HandleProcessCorruptedStateExceptions]
        static void Main(string[] args)
        {
            try {
                RaiseAccessViolationException();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
  • Tip
默认情况下,C#不能捕获C++程序中产生的异常,但是如果我们给会产生的异常的方法增加一个标签:HandleProcessCorruptedStateExceptions,就可以正常捕捉异常。