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

前端 未结 3 942
陌清茗
陌清茗 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:11

    Does the following not work for you?

    try
    {
        // invoke some unmanaged code
    }
    catch (Error const& err)
    {
        throw gcnew System::Exception(gcnew System::String(err.what()));
    }
    

    Because this certainly works for me:

    #pragma managed(push, off)
    #include 
    
    struct Error
    {
        explicit Error(std::string const& message) : message_(message) { }
        char const* what() const throw() { return message_.c_str(); }
    
    private:
        std::string message_;
    };
    
    void SomeFunc()
    {
        throw Error("message goes here");
    }
    
    #pragma managed(pop)
    
    int main()
    {
        using namespace System;
    
        try
        {
            try
            {
                SomeFunc();
            }
            catch (Error const& err)
            {
                throw gcnew Exception(gcnew String(err.what()));
            }
        }
        catch (Exception^ ex)
        {
            Console::WriteLine(ex->ToString());
        }
        Console::ReadLine();
    }
    

提交回复
热议问题