我正在一个大型非托管 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*) 因为那是MCDN 推荐 http://msdn.microsoft.com/en-us/library/aa712787%28v=vs.71%29.aspx
以下内容对您不起作用吗?
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)