簡體   English   中英

我的 Swift 代碼使用 UnsafeMutablePointer 是否安全和/或產生未定義的行為?

[英]Will my Swift code using UnsafeMutablePointer be safe and/or produce undefined behaviour?

I have a C library I need to use in my Swift code and a function thet expects an UnsafeMutablePointer<UInt8> that is 32 bytes long to generate a public key from an existing private key ( crypto_sign_public_key ). 這是 C function 的文檔的鏈接: https://monocypher.org/manual/sign 我對 C 和指針沒有太多經驗,但我已經閱讀了一些教程並且有些東西似乎工作得很好。

除此之外,我想看看是否有比我更有經驗的人能夠說出這段代碼是否“安全”和/或是否會產生未定義的行為?

func generatePublicKey(from privateKey: [UInt8]) -> [UInt8] {
    /// Create an empty pointer that is 32 bytes long. The resulting public key will be written to the memory the pointer is pointing to.
    let publicKeyPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 32)
        
    /// This is using the 25519 curve and the Blake2b hash method.
    /// Sign the private key and in turn, create the public key.
    crypto_sign_public_key(publicKeyPointer, privateKey)
        
    /// Go over the 32 bytes of the pointer and save it's locations as a "buffer"
    let buffer = UnsafeMutableBufferPointer(start: publicKeyPointer, count: 32)
        
    /// Copy the data being pointed to, into an actual array.
    let publicKey = Array(buffer)
        
    /// Deallocate the memory being used by the pointer.
    publicKeyPointer.deallocate()
        
    return publicKey
}

謝謝!

您的代碼沒問題,因為UInt8是一個普通類型,因此不需要您在分配的deinitialize上調用initialize或取消初始化。

但是,您可以完全避免手動分配和釋放,如下所示:

func makePublicKey(withPrivateKey privateKey: [UInt8]) -> [UInt8] {
    var publicKey = [UInt8](repeating: 0, count: 32)
    publicKey.withUnsafeMutableBufferPointer { buffer in
        crypto_sign_public_key(buffer.baseAddress!, privateKey)
    }
    return publicKey
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM