none
Handling user-defined exceptions from C++ DLL - .NET PInvoke/Marshalling. RRS feed

  • Question

  • I am working on WPF application which internally calls a C/C++ DLL using PInvoke. In the debug mode of the DLL, whenever error occurs the function throw an exception which is basically a structure defined containing specific error message and application code specific to module. This is different from the normal Win32 error logging. Now my problem is I want to catch the exception thrown by the DLL.
    If in use a try catch around the Marshalled function, .NET just informed me saying something wrong happened in the external module.
    try
    {
        // Marshalled function called
    }
    catch(Exception ex)
    {
        MessageBox.show(ex.Message);
    }
    

    Now I understand the C/C+= DLL exception is not a class derived from Exception class of .NET hence .NET would not be able to marshal it properly. I cannot change the C++ DLL to managed one or make any source code changes to the dll code.
    I did see a similar post on MSDN with the solution provided in VC++.NET where each function of DLL is created into a wrapper throwing an exception derived from .NET class.
    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0624f3b3-5244-4cb8-be9c-29d464975d20
    However, this would require another .net assembly project which would create wrappers around some 200 functions and structures in VC++.NET. Right now, all the DLL functions have been imported into WPF application using PInvoke so any add-on to existing scenario would be preferred.

    Kavitesh Singh.
    Wednesday, July 20, 2011 1:19 PM

Answers

  •  

    Hi Kavitesh,

     

    I'm afraid that it may be difficult to achieve your purpose. Actually, in .NET world, there are many exceptions that can not be caught. Exceptions thrown of the application firstly is first-chance exceptions, if they can not be handled by the application, it would turn to be a second-chance exception that may crash the whole process.

    Unfortunately, you have encountered a second-chance exception. I think you'd better try to find the root cause instead of handling the exception.

     

    Have a nice day.


    Paul Zhou [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Proposed as answer by Paul Zhou Wednesday, July 27, 2011 6:38 AM
    • Marked as answer by Paul Zhou Thursday, July 28, 2011 3:03 AM
    Tuesday, July 26, 2011 7:00 AM