value e thetedmorey we allocatedHandling UnsafeMutablePointers can be tricky because if it is not done right can leave dangling pointers.
Let’s for example the following method:
The method expects two dangling pointers as arguments.
In order to be on the safe side we have first to initialise and allocate the space to our two variables:
1 2 3 |
let capacity = 32 let pk = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity) let sk = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity) |
The next step is to make sure we place the right input data to these variables:
1 2 3 4 |
for i in 0..<capacity { (pk + i).initialize(to: 0) (sk + i).initialize(to: input[i]) } |
Now we pass these variables in our method call:
1 |
modified_crypto_sign_publickey(pk, sk) |
Now we must deallocate the memory we allocated but before we do that lets save to another variable the variable:
1 2 3 4 |
var pkCopy: [UInt8] = Array(repeating: 0, count: capacity) for i in 0..<capacity { pkCopy[i] = (pk + i).pointee } |
And lastly we deallocate the memory:
1 2 |
pk.deallocate() sk.deallocate() |
There are two WWDC videos regarding Unsafe Swift:
https://developer.apple.com/videos/play/wwdc2020/10648/
https://developer.apple.com/videos/play/wwdc2020/10167/