luciy
(Dzmitry Valkovich)
1
Hello, i work with pointers in my app. And compilation of something like this gives me a warning at the second line: "Initialization of 'UnsafeBufferPointer' results in a dangling buffer pointer."
And i don't get it. The lifetime of the array should be till the end of the block. Why compiler says that arrayPtr is a dangling pointer? Thank you.
do {
var array = [0, 1, 2, 3, 4]
let ptrToArray = UnsafeBufferPointer<Int>(start: &array, count: array.count)
for number in ptrToArray {
print(number)
}
}
AlexanderM
(Alexander Momchilov)
2
The lifetime of the array should be till the end of the block.
The lifetime lasts until the last usage (not necessarily the end of the block), although I recall there were talks about changing that in some up-coming Swift version.
The array could be dropped as early as the completion of the UnsafeBufferPointer.init(start:count:) call.
1 Like
dnadoba
(David Nadoba)
3
You should use array.withUnsafeBufferPointer or a variant of it instead:
let array = [0, 1, 2, 3, 4]
array.withUnsafeBufferPointer { ptrToArray in
for number in ptrToArray {
print(number)
}
}
9 Likes
Karl
(👑🦆)
4
It isn't just the lifetime of the Array that's the issue - &array may copy in to a temporary and only give you the address of that temporary. I believe this can happen for bridged NSArray subclasses, which may not necessarily have contiguous storage.
@dnadoba's suggestion is correct if you really, truly need a pointer. And ideally, the only reason you might need one is for C interop.
13 Likes
luciy
(Dzmitry Valkovich)
5
Thanks for such a complete answer!
Topic is closed