[swift-users] How to malloc in Swift 3
jgroff at apple.com
Fri Sep 23 15:23:14 CDT 2016
> On Sep 23, 2016, at 1:55 AM, Gerriet M. Denkmann via swift-users <swift-users at swift.org> wrote:
>> On 23 Sep 2016, at 15:47, Gerriet M. Denkmann via swift-users <swift-users at swift.org> wrote:
>> This used to work in Swift 2.2:
>> var bitfield: UnsafeMutablePointer<UInt8>?
>> bitfield = UnsafeMutablePointer<UInt8>( malloc( 888 ) )
>> How is this written in Swift 3.0?
> To answer my own question:
> This works:
> var bitfield: UnsafeMutableRawPointer
> bitfield = UnsafeMutableRawPointer( malloc(888))
> But then this stops working:
> let theByte = self.bitfield[ 5 ]
> Somehow the bitfield must know that it is a field of bytes (not shorts, ints or whatever). But how?
The RawPointer types provide methods that can load a value with a given offset and type for you. IIRC, `bitfield.load(fromByteOffset: 0, as: UInt8.self)` will do what you want.
More information about the swift-users