[swift-users] UnsafeMutablePointer on the stack?
Dave Abrahams
dabrahams at apple.com
Sun Oct 2 19:04:00 CDT 2016
on Sun Oct 02 2016, Jean-Denis Muys <swift-users-AT-swift.org> wrote:
> Hi,
>
> I have some issues using the new raw memory API. For instance, let's
> suppose I want to call the `SecRandomCopyBytes` API to generate a
> cryptographically secure random 32-bit number. The difficulty is its 3rd
> argument, which is declared as UnsafeMutablePointer<UInt8>. Here is a
> function that does that:
>
> func entropicRandom() -> UInt32 {
>
> let randomWordPT = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
>
> let _ = randomWordPT.withMemoryRebound(to: UInt8.self, capacity: 4) {
> (p: UnsafeMutablePointer<UInt8>) -> Int32 in
>
> let result = SecRandomCopyBytes(kSecRandomDefault, MemoryLayout<
> UInt32>.size, p)
>
> return result
>
> }
>
> let randomInt32 = randomWordPT[0]
>
> randomWordPT.deallocate(capacity: 1)
>
> return randomInt32
>
> }
>
> apparently, the calls to allocate and then deallocate suggest that there is
> some heap allocation happening behind the scene here, possibly malloc/free.
> Is that correct?
Quite so.
But what did you suppose allocate and deallocate did, if not dynamic
memory allocation?
> If so, this is quite wasteful. Is there a way to use a local variable on
> the stack to achieve the same result?
func entropicRandom() -> UInt32 {
var randomInt32: UInt32 = 0
let byteCount = MemoryLayout.size(ofValue: randomInt32)
withUnsafeMutablePointer(to: &randomInt32) {
$0.withMemoryRebound(to: UInt8.self, capacity: byteCount) {
SecRandomCopyBytes(kSecRandomDefault, byteCount, $0)
}
}
return randomInt32
}
HTH,
--
-Dave
More information about the swift-users
mailing list