How to catch unmanaged C++ exception in managed C++

前端 未结 3 954
陌清茗
陌清茗 2021-02-08 02:42

I am developing a thin managed C++ wrapper over a large unmanaged C++ library, and a large C# library. I need to catch errors originating in that large unmanaged C++ library, an

3条回答
  •  悲哀的现实
    2021-02-08 03:18

    I use

    #include 
    #include 
    
    using namespace System;
    using namespace msclr::interop;
    
    try
    {
        ...
    }
    
    catch (const std::exception& e)
    {
        throw gcnew Exception(marshal_as(e.what()));
    }
    
    catch (...)
    {
        throw gcnew Exception("Unknown C++ exception");
    }
    

    You may want to put this into a pair of macros since they'll be used everywhere.

    You can add a custom catch block with your Error class, but since it seems to derive from std::exception, the code I show you should be OK.

    You could also want to catch more specifically std::invalid_argument and translate it into ArgumentException, etc. but I find this overkill.

提交回复
热议问题