Cannot invoke initializer for type UnsafePointer<_> with an argument list of type (UnsafeMutableRawPointer)

守給你的承諾、 提交于 2019-12-10 11:17:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!