[swift-users] NSData and UnsafePointer

J.E. Schotsman jeschot at xs4all.nl
Mon Jul 18 13:54:47 CDT 2016


> On 16 Jul 2016, at 22:16, Andrew Trick <atrick at apple.com> wrote:
> 
> 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)
> }

I tried that but got a compiler crash (segmentation fault 11)
So I improvised my own withExtendedLifetime by extending NSData with a doNothing() method which sets a field in a global struct.

let dataStart = UnsafePointer<CChar>(data.bytes)
 myProcessdata1(dataStart,data.length)
data.doNothing()

but this didn’t help. Apparently this is not a lifetime bug.

The code that crashed looked like this:

init() throws
	{
	let data = ...
	do { try withExtendedLifetime(data)
		{
		let ptr = UnsafePointer<Int8>(data.bytes)
		do { try super.init(dataPtr:ptr, dataLength: data.length) ) }
		}}
	}

Calling super.init in a closure is probably illegal anyway.

I wonder, would Whole Module Optimization notice that doNothing() does nothing (i.e. the field in the global struct is never read) and remove it?

Jan E.


More information about the swift-users mailing list