Deepak Sharma
Deepak Sharma

Reputation: 6477

Swift Struct Warning "Initialization of 'UnsafeMutableRawPointer' results in a dangling pointer"

I searched many answers for similar questions but can't find the right answer that fixes this. I have a very simple struct

  struct MyParameters {
    var position: CGPoint
    var size: Float
  }

And then this initialisation

 var parameters = MyParameters(position: .zero, size: 0)
 let pointer = UnsafeMutableRawPointer(&parameters)

And I get a warning in the second line

 Initialization of 'UnsafeMutableRawPointer' results in a dangling pointer

I understand the compiler is complaining as it is not sure whether the memory pointed to by the pointer will continue to exist. But what is the right way to pass pointers in that case?

Upvotes: 0

Views: 288

Answers (1)

Gereon
Gereon

Reputation: 17844

Use withUnsafeMutableBytes

func foo() {
    var parameters = MyParameters(position: .zero, size: 0)
    
    withUnsafeMutableBytes(of: &parameters) { pointer in
         // here the lifetime is known
    }
}

Upvotes: 1

Related Questions