如何在托管C++中捕获非托管C++异常

Arn*_*und 11 .net c# error-handling c++-cli

我正在一个大型非托管C++库和一个大型C#库上开发一个瘦托管C++包装器.我需要捕获源自该大型非托管C++库的错误,并将它们重新抛出为Clr异常.非托管库抛出以下类的实例:

Error::Error(const std::string& file, long line,
             const std::string& function,
             const std::string& message) {
    message_ = boost::shared_ptr<std::string>(new std::string(
                                  format(file, line, function, message)));
}

const char* Error::what() const throw () {
    return message_->c_str();
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经想出了这个:

try{
// invoke some unmanaged code
}
catch(Object*)
{
throw gcnew System::Exception("something bad happened");
}
Run Code Online (Sandbox Code Playgroud)

如何从Error类中提取消息并将其转换为Clr String类,以便我可以将它传递给gcnew System :: Exception()构造函数?如果非托管代码抛出其他内容,我的catch块会抓住它吗?

编辑:我正在使用catch(Object*),因为在MCDN中建议使用它

ild*_*arn 9

以下不适合您吗?

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

因为这对我来说当然有用:

#pragma managed(push, off)
#include <string>

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();
}
Run Code Online (Sandbox Code Playgroud)


Ale*_* C. 5

我用

#include <exception>
#include <msclr\marshal.h>

using namespace System;
using namespace msclr::interop;

try
{
    ...
}

catch (const std::exception& e)
{
    throw gcnew Exception(marshal_as<String^>(e.what()));
}

catch (...)
{
    throw gcnew Exception("Unknown C++ exception");
}
Run Code Online (Sandbox Code Playgroud)

您可能希望将其放入一对宏中,因为它们将在任何地方使用。

您可以在catch您的Error类中添加自定义块,但由于它似乎是从 派生的std::exception,因此我向您展示的代码应该没问题。

您还可以更具体地捕捉std::invalid_argument并将其翻译成ArgumentException等,但我觉得这太过分了。