> On Jul 16, 2016, at 5:28 AM, J.E. Schotsman via swift-users 
> <swift-users@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.

There’s also the problem of potentially casting your UnsafePointer to something 
other than CChar, but that’s not really the issue at hand.

> And this:
> 
> let data:NSData = …
> myProcessdata2(data)
> 
> … (no more references to data)
> 
> func myProcessdata2( data:NSData )
> {
> let dataStart = UnsafePointer<CChar>(data:NSData.bytes)
> myProcessdata1(dataStart,data.length)
> }
> 
> In the latter case I would hope that data remains alive until the function 
> myProcessdata2 returns. But does it?

I think the latter case has the same problems as the former.

-Andy

> 
> TIA,
> 
> Jan E.
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to