在我的iOS项目中,我使用一个C++模块。C++模块在某些情况下抛出异常,目标C++包装器无法捕获它。例如
这是我的HelloWorld.h
#include <string>
using namespace std;
class HelloWorld{
public:
string helloWorld();
};
#endif实现HelloWorld.cpp
#include "HelloWorld.h"
string HelloWorld::helloWorld(){
throw (std::runtime_error("runtime_error")); // Throwing exception to test
string s("Hello from CPP");
return s;
}目标C++包装器HelloWorldIOSWrapper.h
#import <Foundation/Foundation.h>
@interface HelloWorldIOSWrapper:NSObject
- (NSString*)getHello;
@end
#endif /* HelloWorldIOSWrapper_h */实现HelloWorldIOSWrapper.mm
#import "HelloWorldIOSWrapper.h"
#include "HelloWorld.h"
@implementation HelloWorldIOSWrapper
- (NSString*)getHello{
try {
HelloWorld h;
NSString *text=[NSString stringWithUTF8String: h.helloWorld().c_str()];
return text;
} catch (const std::exception & e) {
NSLog(@"Error %s", e.what());
}
return nil;
}
@end#import "HelloWorldIOSWrapper.h"被添加到Bridging-Header中
现在,当我试图从控制器调用getHello()时,应用程序崩溃,在日志中留下以下消息
libc++abi: terminating with uncaught exception of type std::runtime_error: runtime_error
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
terminating with uncaught exception of type std::runtime_error: runtime_error我希望这个异常必须在包装器中捕获,但是,我不知道为什么它不会导致应用程序崩溃。我错过了什么?
发布于 2022-07-14 14:07:36
在64位进程中,目标C异常(NSException)和C++异常是可互操作的.具体来说,当异常机制解除异常时,C++析构函数和Objective @finally块将得到遵守。此外,默认catch子句--即catch(.)和@ catch (.)-can捕获并重新抛出任何异常 另一方面,接受动态类型异常对象(@ catch (id异常))的object -C catch子句可以捕获任何对象-C异常,但不能捕获任何C++异常。因此,为了实现互操作性,请使用@(.)捕获每个异常和@抛出;重新抛出捕获的异常。在32位中,@ catch (.)具有与@catch(id异常)相同的效果。
@try {
}
@catch (...) {
}https://stackoverflow.com/questions/72980035
复制相似问题