问题
When I write the output stream in multipeer connectivity from audio buffer data I got the error
Cannot invoke initializer for type UnsafePointer<_> with an argument list of type (UnsafeMutableRawPointer)
I found the many solutions, but this solution not helpful for me.
My code is:
func send(_ buffer: AudioBuffer) {
print(buffer.mData!)
print(buffer.mDataByteSize)
outputStreme?.write(UnsafePointer(buffer.mData), maxLength: buffer.mDataByteSize)
}
Thanks in advance..:)
回答1:
Please check the official reference when some sort of spec changes has affected with your code. In your case AudioBuffer.mData
is of type UnsafeMutableRawPointer?
, and you need to pass it to the first argument of OutputStream.write(_:maxLength:)
of type UnsafePointer<UInt8>
.
UnsafeMutableRawPointer
You can find this method which returns UnsafeMutablePointer<T>
:
func assumingMemoryBound<T>(to: T.Type)
The concept of bound is sort of confusing, but seems you can use it for pointer type conversion:
outputStreme?.write(buffer.mData!.assumingMemoryBound(to: UInt8.self), maxLength: Int(buffer.mDataByteSize))
(Assuming forced-unwrapping !
is safe enough as suggested by your print(buffer.mData!)
.)
Memory bound-ness is not well defined for most APIs which return pointers, and has no effect as for now. There's another type conversion method func bindMemory<T>(to: T.Type, capacity: Int), and both work without problems (again, as for now).
回答2:
Try this :
withUnsafePointer(to: &data) {rawUuidPtr in //<- `rawUuidPtr` is of type `UnsafePointer<uuid_t>`.
let bytes = UnsafeRawPointer(rawUuidPtr).assumingMemoryBound(to: UInt8.self)
outputStream.write(bytes, maxLength: 4)
}
来源:https://stackoverflow.com/questions/45181614/cannot-invoke-initializer-for-type-unsafepointer-with-an-argument-list-of-typ