gpt4 book ai didi

从 mach_timebase_info() 创建一个结构

转载 作者:搜寻专家 更新时间:2023-11-01 05:51:30 25 4
gpt4 key购买 nike

在 C 中创建时基信息结构很容易,但在 Swift 中,以下内容在 playground 中不起作用:

让 timebaseInfo: mach_timebase_info_data_t = mach_timebase_info(&timebaseInfo)

错误是Variable used within its own initial value

我理解这个错误,但我无法想出一种方法来做到这一点而不下降到 C。是否有我缺少的 Swift 唯一方法?任何帮助将不胜感激。 :-)

编辑:实际上我看到上面的“A”问题,“=”没有意义。但我也尝试了以下方法:

let timebaseInfo: mach_timebase_info_data_t
mach_timebase_info(&timebaseInfo)'

初始化前使用的 timebasedInfo 出错。 :-(

最佳答案

mach_timebase_info函数声明为

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

这意味着您可以传递一个(已初始化的)mach_timebase_info多变的作为 & 的“输入输出表达式” :

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

有关详细信息,请参阅 Interacting with C APIs在“将 Swift 与 Cocoa 和 Objective-C 结合使用”手册中:

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

关于从 mach_timebase_info() 创建一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com