如何通过引用将 UnsafePointer<UInt8> 传递给 C API?
How to pass an UnsafePointer<UInt8> to a C API by reference?
我写了一些 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
不幸的是,由于这个错误,我无法再通过引用将 ptr
传递给 ASN1_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)?
但后来我被告知我现有的赋值 已经 产生一个可选的
- 将
UnsafePointer
更改为 UnsafeMutablePointer
这里需要更改什么?
问题似乎是 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 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
不幸的是,由于这个错误,我无法再通过引用将 ptr
传递给 ASN1_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)?
但后来我被告知我现有的赋值 已经 产生一个可选的 - 将
UnsafePointer
更改为UnsafeMutablePointer
这里需要更改什么?
问题似乎是 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))
}
(*)
是使其编译的指针转换。