我試圖從托管代碼中拋出一個 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");
...然后該字串被傳遞并由 ex.what() 回傳。我也試過...
throw std::runtime_error(myExMsg);
...但 ex.what() 只回傳一個以 '\x7F' 結尾的字串(以防萬一)。
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)?
uj5u.com熱心網友回復:
根據@Joe 的建議,我繼承自 std::exception ...
class InvokeException : public std::exception {
public:
InvokeException(std::string const& message) : msg_(message) { }
virtual char const* what() const noexcept { return msg_.c_str(); }
private:
std::string msg_;
};
... 然后 ...
const std::string myExMsg = msclr::interop::marshal_as<std::string>(ex->Message);
throw InvokeException(myExMsg);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449986.html
標籤:c string exception c -cli std
