gpt4 book ai didi

swift - 如何通过引用将 UnsafePointer 传递给 C API?

转载 作者:搜寻专家 更新时间:2023-10-31 22:30:13 25 4
gpt4 key购买 nike

我写了一些 Swift 2.2 代码来与 OpenSSL 交互C API,现在我正在尝试将其转换为 Swift 3。

在 swift 2 中

let octets = pkcs7_d_data(pkcs7_d_sign(receiptPKCS7).memory.contents)
var ptr = UnsafePointer<UInt8>(octets.memory.data)

// now pass pointer by reference
ASN1_get_object(&ptr, &length, &type, &xclass, end - ptr)

在 Swift 3 中,我不得不做一些改变

// use guard so i dont have to constantly unwrap these values

guard let octets = pkcs7_d_data(pkcs7_d_sign(receiptPKCS7).pointee.contents),
var ptr = UnsafePointer<UInt8>(octets.pointee.data) else {
return nil
}

ASN1_get_object(&ptr, &length, &type, &xclass, end - ptr)
// ^^^ this is now a compiler error

不幸的是,我不能再通过ptrASN1_get_object通过引用,由于这个错误:

Cannot pass immutable value as inout argument: Implicit conversion from UnsafePointer<UInt8> to UnsafePointer<UInt8>? requires a temporary

然后其余的错误被切断(没有展开箭头)。

我尝试过的:

  • 更改 ptr分配给 UnsafePointer<UInt8>(octets.pointee.data)?但后来我被告知我现有的任务已经产生了一个可选的
  • 更改了 UnsafePointerUnsafeMutablePointer

这里需要改变什么?

最佳答案

问题似乎是octets.pointee.data是一个 UnsafeMutablePointer<UInt8>! ,但是 ASN1_get_object期望UnsafePointer<UInt8>? 的地址.

以下代码可以编译,但我无法对其进行测试:

if
let octets = pkcs7_d_data(pkcs7_d_sign(receiptPKCS7).pointee.contents),
let data = octets.pointee.data {

var ptr: UnsafePointer? = UnsafePointer(data) // (*)
var length = 0
var tag: Int32 = 0
var xclass: Int32 = 0

ASN1_get_object(&ptr, &length, &tag, &xclass, Int(octets.pointee.length))
}

(*)是使其编译的指针转换。

关于swift - 如何通过引用将 UnsafePointer<UInt8> 传递给 C API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39902248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com