在objective-c中,我可以调用代码来获取回溯
void* callstack[128];
int frames = backtrace(callstack, 128);
char **strs = backtrace_symbols(callstack, frames);
按导入#include <execinfo.h>
但是在swift中,如何调用backtrace
和backtrace_symbols
,我无法找到execinfo
文件
答案 0 :(得分:4)
在Swift 3中,您只需使用即可打印堆栈回溯 (来自How to print call stack in Swift?):
for symbol in Thread.callStackSymbols {
print(symbol)
}
但是如果你很好奇如何将C代码翻译成Swift: 首先添加
#include <execinfo.h>
到桥接头文件以生成backtrace()
函数
可用。然后请注意void *
对应
在Swift中UnsafeMutableRawPointer?
,你差不多完成了:
var callstack = [UnsafeMutableRawPointer?](repeating: nil, count: 128)
let frames = backtrace(&callstack, Int32(callstack.count))
if let symbols = backtrace_symbols(&callstack, frames) {
for frame in 0..<Int(frames) where symbols[frame] != nil {
let symbol = String(cString: symbols[frame]!)
print(symbol)
}
free(symbols)
}
答案 1 :(得分:1)
@_silgen_name("backtrace")
internal func swift_backtrace(_ callstacks: UnsafeMutableRawPointer, _ counts: Int) -> Int
@_silgen_name("backtrace_symbols")
internal func swift_backtrace_symbols(_ callstacks: UnsafeRawPointer, _ counts: Int) -> UnsafeMutablePointer<UnsafePointer<CChar>>?
var callstack = [UnsafeMutableRawPointer?](repeating: nil, count: 128)
let frames = swift_backtrace(&callstack, callstack.count)
if let symbols = swift_backtrace_symbols(&callstack, frames) {
for frame in 0..<frames {
let symbol = String(cString: symbols[frame])
print(symbol)
}
free(symbols)
}