如何在 Swift 中调用 backtrace_symbols()

How to call backtrace_symbols() in Swift

在Objective-C中,我可以调用代码获取backtrace

void* callstack[128];
int frames = backtrace(callstack, 128);
char **strs = backtrace_symbols(callstack, frames);

通过导入 #include <execinfo.h>

但在 Swift 中,我如何调用 backtracebacktrace_symbols,我无法在任何地方找到 execinfo 文件。

在 Swift 3 中,您可以简单地打印堆栈回溯 (来自 How to print call stack in Swift?):

for symbol in Thread.callStackSymbols {
    print(symbol)
}

但如果您对如何将 C 代码转换为 Swift 感到好奇: 先加

#include <execinfo.h>

到桥接头文件以创建 backtrace() 函数 可用的。然后注意 void * 对应 UnsafeMutableRawPointer? 在 Swift,你快完成了:

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)
}

@_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)
}