Search code examples
swiftbacktrace

How to call backtrace_symbols() in Swift


In Objective-C, I can call the code to get backtrace

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

by import #include <execinfo.h>

but in Swift, how can I call backtrace and backtrace_symbols, I can't find execinfo file any where.


Solution

  • In Swift 3 you can print the stack backtrace simply with (from How to print call stack in Swift?):

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

    But if you are curious how to translate the C code to Swift: First add

    #include <execinfo.h>
    

    to the bridging header file to make the backtrace() function available. Then note that void * corresponds to UnsafeMutableRawPointer? in Swift, and you are almost done:

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