有没有办法将Swift结构地址强制转换为void UnsafeMutablePointer?
我试了这个没有成功:
struct TheStruct {
var a:Int = 0
}
var myStruct = TheStruct()
var address = UnsafeMutablePointer<Void>(&myStruct)
谢谢!
编辑:上下文
我实际上是在尝试将 Learning CoreAudio 中的第一个示例移植到Swift
这就是我到目前为止所做的事情:
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 ......不要。 (阅读评论以获取详细信息)
答案 0 :(得分:17)
据我所知,最简短的方法是:
var myStruct = TheStruct()
var address = withUnsafeMutablePointer(&myStruct) {UnsafeMutablePointer<Void>($0)}
但是,为什么你需要这个?如果你想把它作为参数传递,你可以(并且应该):
func foo(arg:UnsafeMutablePointer<Void>) {
//...
}
var myStruct = TheStruct()
foo(&myStruct)
答案 1 :(得分:0)
随着多年来Swift的发展,大多数方法原型都已更改。这是 Swift 5 的语法:
var struct = TheStruct()
var unsafeMutablePtrToStruct = withUnsafeMutablePointer(to: &struct) {
$0.withMemoryRebound(to: TheStruct.self, capacity: 1) {
(unsafePointer: UnsafeMutablePointer<TheStruct>) in
unsafePointer
}
}