将 Swift 结构转换为 UnsafeMutablePointer<Void>
Cast a Swift struct to UnsafeMutablePointer<Void>
有没有办法将 Swift 结构的地址转换为 void UnsafeMutablePointer?
我试过了但没有成功:
struct TheStruct {
var a:Int = 0
}
var myStruct = TheStruct()
var address = UnsafeMutablePointer<Void>(&myStruct)
谢谢!
编辑:上下文
我实际上正在尝试移植到 Swift Learning CoreAudio.
中的第一个示例
这是我到目前为止所做的:
func myAQInputCallback(inUserData:UnsafeMutablePointer<Void>,
inQueue:AudioQueueRef,
inBuffer:AudioQueueBufferRef,
inStartTime:UnsafePointer<AudioTimeStamp>,
inNumPackets:UInt32,
inPacketDesc:UnsafePointer<AudioStreamPacketDescription>)
{ }
struct MyRecorder {
var recordFile: AudioFileID = AudioFileID()
var recordPacket: Int64 = 0
var running: Boolean = 0
}
var queue:AudioQueueRef = AudioQueueRef()
AudioQueueNewInput(&asbd,
myAQInputCallback,
&recorder, // <- this is where I *think* a void pointer is demanded
nil,
nil,
UInt32(0),
&queue)
我正在努力留在 Swift,但如果事实证明这是一个问题而不是优势,我将最终链接到 C 函数。
编辑:底线
如果您因为尝试在 Swift 中使用 CoreAudio 的 AudioQueue 而遇到这个问题...请不要。 (阅读评论了解详情)
据我所知,最短的路是:
var myStruct = TheStruct()
var address = withUnsafeMutablePointer(&myStruct) {UnsafeMutablePointer<Void>([=10=])}
但是,你为什么需要这个?如果你想将它作为参数传递,你可以(并且应该):
func foo(arg:UnsafeMutablePointer<Void>) {
//...
}
var myStruct = TheStruct()
foo(&myStruct)
随着 Swift 多年来的发展,大多数方法原型都发生了变化。这是 Swift 5:
的语法
var struct = TheStruct()
var unsafeMutablePtrToStruct = withUnsafeMutablePointer(to: &struct) {
[=10=].withMemoryRebound(to: TheStruct.self, capacity: 1) {
(unsafePointer: UnsafeMutablePointer<TheStruct>) in
unsafePointer
}
}
有没有办法将 Swift 结构的地址转换为 void UnsafeMutablePointer?
我试过了但没有成功:
struct TheStruct {
var a:Int = 0
}
var myStruct = TheStruct()
var address = UnsafeMutablePointer<Void>(&myStruct)
谢谢!
编辑:上下文
我实际上正在尝试移植到 Swift Learning CoreAudio.
中的第一个示例
这是我到目前为止所做的:
func myAQInputCallback(inUserData:UnsafeMutablePointer<Void>,
inQueue:AudioQueueRef,
inBuffer:AudioQueueBufferRef,
inStartTime:UnsafePointer<AudioTimeStamp>,
inNumPackets:UInt32,
inPacketDesc:UnsafePointer<AudioStreamPacketDescription>)
{ }
struct MyRecorder {
var recordFile: AudioFileID = AudioFileID()
var recordPacket: Int64 = 0
var running: Boolean = 0
}
var queue:AudioQueueRef = AudioQueueRef()
AudioQueueNewInput(&asbd,
myAQInputCallback,
&recorder, // <- this is where I *think* a void pointer is demanded
nil,
nil,
UInt32(0),
&queue)
我正在努力留在 Swift,但如果事实证明这是一个问题而不是优势,我将最终链接到 C 函数。
编辑:底线
如果您因为尝试在 Swift 中使用 CoreAudio 的 AudioQueue 而遇到这个问题...请不要。 (阅读评论了解详情)
据我所知,最短的路是:
var myStruct = TheStruct()
var address = withUnsafeMutablePointer(&myStruct) {UnsafeMutablePointer<Void>([=10=])}
但是,你为什么需要这个?如果你想将它作为参数传递,你可以(并且应该):
func foo(arg:UnsafeMutablePointer<Void>) {
//...
}
var myStruct = TheStruct()
foo(&myStruct)
随着 Swift 多年来的发展,大多数方法原型都发生了变化。这是 Swift 5:
的语法var struct = TheStruct()
var unsafeMutablePtrToStruct = withUnsafeMutablePointer(to: &struct) {
[=10=].withMemoryRebound(to: TheStruct.self, capacity: 1) {
(unsafePointer: UnsafeMutablePointer<TheStruct>) in
unsafePointer
}
}