TimesToCome Mobile

iOS apps and tips, tricks and tools for smart phones

Swift data to C pointer and back again




I’ve been converting my hardware sensor app from ObjC to Swift. Today I converted the sound which was easier than expected till I had to de-reference the data pointer. Hours later I have it working.

Here are the basics for converting back and forth from C pointers and Swift

let data:UInt8 = 42 // Swift 8bit int
let ps = UnsafeMutablePointer.alloc(1) // alloc one memory location
ps.initialize(data) // put the data in the memory location

let dataOut = UnsafeMutablePointer(ps) // cast the C pointer to Swift pointer
let original:UInt8 = ps.memory // grab the data and cast it to a Swift Int8

// ———— for sound capture ———————————————–

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {

let formatDescriptionRef = CMSampleBufferGetFormatDescription(sampleBuffer)
let formatDescription = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescriptionRef)

var totalBytes = 0 as UInt64

let blockBufferRef = CMSampleBufferGetDataBuffer(sampleBuffer)
var lengthOfBlock = CMBlockBufferGetDataLength(blockBufferRef)

var data = NSMutableData(length: Int(lengthOfBlock))
CMBlockBufferCopyDataBytes(blockBufferRef, 0, lengthOfBlock, data.mutableBytes)

var samples = UnsafeMutablePointer(data.mutableBytes)
var value:UInt8 = samples.memory

}