SubCycle SubCycle - 8 days ago 6
Swift Question

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 the swift, how can I call
backtrace
and
backtrace_symbols
,I cant find
execinfo
file any where

Answer

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