c# – 如何在托管C中捕获非托管C异常
发布时间:2020-12-15 06:25:17  所属栏目:百科  来源:网络整理 
            导读:我正在一个大的非托管C库和一个大型C#库开发一个瘦的托管C包装.我需要捕获源自该大型非托管C库的错误,并将其作为Clr异常重新抛出.非托管库抛出以下类的实例: Error::Error(const std::string file,long line,const std::string function,const std::string
                
                
                
            | 我正在一个大的非托管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(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();
}(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
