Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a struct from mach_timebase_info()

Tags:

c

swift

Creating a time base info struct in C is easy, but in Swift the following does not work in the playground:

let timebaseInfo: mach_timebase_info_data_t = mach_timebase_info(&timebaseInfo)

The error is Variable used within its own initial value

I understand the error, but I am unable to think of a way to do this without dropping down to C. Is there a Swift only way that I am missing? Any help would be greatly appreciated. :-)

Edit: Actually I see "A" problem with the above, the "=" doesn't make sense. But I did try the following also:

let timebaseInfo: mach_timebase_info_data_t
mach_timebase_info(&timebaseInfo)'

With an error stating timebasedInfo used before initialization. :-(

like image 761
text segment Avatar asked May 21 '26 09:05

text segment


2 Answers

The mach_timebase_info function is declared as

typealias mach_timebase_info_t = UnsafeMutablePointer<mach_timebase_info>
// ...
func mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t

which means that you can pass an (initialized) mach_timebase_info variable as an "in-out expression" with &:

var timebaseInfo = mach_timebase_info(numer: 0, denom: 0)
let status = mach_timebase_info(&timebaseInfo)
if status == KERN_SUCCESS {
    // ...
}

For more information, see Interacting with C APIs in the "Using Swift with Cocoa and Objective-C" manual:

Mutable Pointers

When a function is declared as taking an UnsafeMutablePointer<Type> argument, it can accept any of the following:

  • nil, which is passed as a null pointer
  • An UnsafeMutablePointer<Type> value
  • An in-out expression whose operand is a stored lvalue of type Type, which is passed as the address of the lvalue
  • An in-out [Type] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call
like image 171
Martin R Avatar answered May 23 '26 01:05

Martin R


You'll need to use UnsafeMutablePointer<Type>, as follows:

let p = UnsafeMutablePointer<mach_timebase_info_data_t>.alloc(1)
mach_timebase_info(&p.memory)
like image 34
Stuart Carnie Avatar answered May 23 '26 00:05

Stuart Carnie