将 std::exception 中的消息从托管代码传递到非托管代码
我试图从托管代码中抛出 std::Exception ,以便它被捕获在非托管代码中。我正在努力的地方是传递一个字符串(描述异常),以便可以使用 What() 方法检查(重新)捕获的异常......
#pragma managed
static std::string InvokeMethod() {
try {
//...
}
catch (Exception^ ex) {
std::string myExMsg = msclr::interop::marshal_as<std::string>(ex->ToString());
throw std::exception(myExMsg);
}
}
#pragma unmanaged
void Execute() {
try {
myMethod = InvokeMethod();
}
catch (std::exception ex) {
SetError(ex.what());
}
}
这不会用 “没有构造函数实例”进行编译stdext:exceptipon::exception" 匹配参数列表参数类型为 (std::string)" 但如果我将字符串放入 std::exception 中,就像这样.. ...
throw std::exception("An error has occurred");
然后该字符串被传递并返回例如什么()。我也尝试过……
throw std::runtime_error(myExMsg);
但是 ex.what() 只是返回一个以 '\x7F' 结尾的字符串(如果这是一个线索)。
在我看来, std::exception 需要其他类型。但什么类型呢? 'myExMsg' 需要是什么,以便 ex.what() 返回相同的字符串(可以在 SetError 方法中使用)?
I am trying to throw a std::exception from managed code so that it is caught in unmanaged code. Where I'm struggling is passing a string (describing the exception) so that the (re-)caught exception can be examined using the what() method ...
#pragma managed
static std::string InvokeMethod() {
try {
//...
}
catch (Exception^ ex) {
std::string myExMsg = msclr::interop::marshal_as<std::string>(ex->ToString());
throw std::exception(myExMsg);
}
}
#pragma unmanaged
void Execute() {
try {
myMethod = InvokeMethod();
}
catch (std::exception ex) {
SetError(ex.what());
}
}
This doesn't compile with "no instance of constructor "stdext:exceptipon::exception" matches the argument list argument types are (std::string)" BUT if I 'hard code' a string into std::exception like this ...
throw std::exception("An error has occurred");
... then that string gets passed along and returned by ex.what(). I also tried ...
throw std::runtime_error(myExMsg);
... but ex.what() just returns a string ending with '\x7F' (in case that's a clue).
It looks to me that std::exception is expecting some other type. But what type? What does 'myExMsg' need to be so that ex.what() returns the same string (that can be used in the SetError method)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据@Joe 提出的建议,我继承了 std::exception ...
...然后...
Following suggestion made by @Joe, I inherit from std::exception ...
... and then ...