[swift-users] NSData and UnsafePointer

Dmitri Gribenko gribozavr at gmail.com
Sat Jul 16 15:23:04 CDT 2016


On Sat, Jul 16, 2016 at 1:16 PM, Andrew Trick via swift-users
<swift-users at swift.org> wrote:
>
>> On Jul 16, 2016, at 5:28 AM, J.E. Schotsman via swift-users <swift-users at swift.org> wrote:
>>
>> A mysterious bug has got me thinking about using UnsafePointer<CChar> with NSData (Swift 2).
>>
>> Is this safe:
>>
>> let data:NSData = …
>> let dataStart = UnsafePointer<CChar>(data:NSDAta.bytes)
>>
>> myProcessdata1(dataStart,data.length)
>>
>> … (no more references to data)
>
> I don’t know what the recommended idiom is or if the syntax has changed from Swift 2 to 3, but I would do something like this:
>
> withExtendedLifetime(data) {
>   let dataStart = UnsafePointer<CChar>(data.bytes)
>   myProcessdata1(dataStart,data.length)
> }
>
> UnsafePointers aren’t meant to keep things alive.

This is exactly the reason why Swift 3 changes this API to use the
`data.withUnsafe* {}` idiom.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-users mailing list