【问题标题】:'UnsafePointer<Int8>' is not convertible to 'UnsafePointer<_>'UnsafePointer<Int8>' 不能转换为 'UnsafePointer<_>
【发布时间】:2020-03-22 08:34:33
【问题描述】:

我正在尝试使用 Swift 编写一个围绕 libssh2 的包装器。以下代码用于通过 SFTP 删除文件。

func removeFile(_ path: String) {
    let data = path.data(using: String.Encoding.utf8)!
    let result = data.withUnsafeBytes { (pointer: UnsafePointer<Int8>) -> Int in
        return libssh2_sftp_unlink_ex(sftpHandle, pointer, data.count)
    }
}

对于pointer: UnsafePointer&lt;Int8&gt;,我收到以下错误消息:

'UnsafePointer<Int8>' is not convertible to 'UnsafePointer<_>

我发现this 线程关于UInt8 的类似问题。我尝试删除演员,但只是得到下一个错误:

'Swift.UnsafePointer<_>' is not convertible to 'Swift.UnsafePointer<_>'

使用虚拟指针在闭包外运行libssh2_sftp_unlink_ex(sftpHandle, pointer, data.count) 有效。

我还找到了this关于将字符串转换为UInt8的答案,问题是我无法将它移植到Int8。关于如何正确转换指针的任何想法?

【问题讨论】:

    标签: swift libssh2 unsafe-pointers


    【解决方案1】:

    data.withUnsafeBytesUnsafeRawBufferPointer 调用闭包,这必须“绑定”到UnsafePointer&lt;Int8&gt;。此外,data.count 必须转换为 UInt32(又名 CUnsignedInt),因为这是将 C 类型 unsigned integer 导入 Swift 的方式:

    func removeFile(_ path: String) {
        let data = path.data(using: String.Encoding.utf8)!
        let result = data.withUnsafeBytes {
            libssh2_sftp_unlink_ex(sftpHandle,
                                   $0.bindMemory(to: Int8.self).baseAddress,
                                   UInt32(data.count))
        }
    }
    

    或者,使用StringwithCString()方法:

    func removeFile(_ path: String) {
        let result = path.withCString {
            libssh2_sftp_unlink_ex(sftpHandle, $0, UInt32(strlen($0)))
        }
    }
    

    更简单:使用只需要一个 C 字符串而不是显式字符串长度的变体。这里编译器会自动创建将 Swift 字符串转换为临时 C 字符串的代码:

    func removeFile(_ path: String) {
        let result = libssh2_sftp_unlink(sftpHandle, path)
    }
    

    (不起作用,因为 libssh2_sftp_unlink 是一个 并且没有导入到 Swift。)

    【讨论】:

    • 谢谢,我使用了第二个变体withCString(),效果很好。我也尝试了第三种方法,但不知何故 Xcode 找不到方法libssh2_sftp_unlink。它说未解析的标识符...
    • @Codey:libssh2 将 libssh2_sftp_unlink 定义为宏。显然该宏没有导入到 Swift 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多