views:

156

answers:

1

I have a project that consists of a C# application that calls into a couple of C++/CLI DLLs. If I have a Visual Studio C Runtime Library fatal error in the native code, there appears to be no way to catch it.

To give a simple example, if I put this in the native code:

    wchar_t buf[1];
    ::wcscpy_s(buf, 1, L"ab");

The app will crash (in release builds). It doesn't throw an exception and I can't catch it with _try..._except.

I'd like to catch these kinds of errors so I can display a nice error dialog, ideally with a callstack. I'd settle for creating a minidump, but I tried creating a minidump by calling ::SetUnhandledExceptionFilter() in one of the C++/CLI DLLs but that doesn't appear to work either.

Is there any way to gracefully handle a C Runtime Library fatal error in a .NET application?

A: 

If you have control of the C++ code then you can install a validation handler to make things like the safe string functions return an error rather than aborting the entire applicaiton. See this.

A simple example showing you can even convert the error to a managed exception and exit cleanly:

#include <stdlib.h>
#include <string.h>
using namespace System;

void InvalidParameterHandler(
   const wchar_t * expression,
   const wchar_t * function, 
   const wchar_t * file, 
   unsigned int line,
   uintptr_t pReserved
)
{
    throw gcnew Exception("Argh");
}

int main(array <System::String ^> ^args)
{
    _set_invalid_parameter_handler(InvalidParameterHandler);

    try
    {
        wchar_t buf[1];
        wcscpy_s(buf, 1, L"Hello");
    }
    catch(Exception^ e)
    {
        Console::WriteLine(e->ToString());
    }

    return 0;
}
tyranid