微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何在托管C中捕获非托管C异常

我正在一个大的非托管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();
}

到目前为止我已经想出了这一点:

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

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

编辑:我正在使用catch(Object *),因为这是recommended in MCDN

解决方法

以下不适合你吗?
try
{
    // invoke some unmanaged code
}
catch (Error const& err)
{
    throw gcnew System::Exception(gcnew System::String(err.what()));
}

因为这对我来说肯定有效:

#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();
}

原文地址:https://www.jb51.cc/csharp/95661.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐