[英]How to get length of a UnsafeMutablePointer<Object> written to a OpenSSL BIO in Swift?
I'm working with OpenSSL and therefore am having to work with some UnsafeMutablePointer
objects.我正在使用 OpenSSL,因此必须使用一些
UnsafeMutablePointer
对象。
I'm running the following code我正在运行以下代码
var x509_REQ : UnsafeMutablePointer<X509_REQ> = someObject
let b = BIO_new(BIO_s_mem())
let size = 3000
let status = i2d_X509_REQ_bio(b, x509_REQ)
guard status == 1 else{
BIO_free(b)
return "Failed to execute i2d_X509_REQ_bio command"
}
let bp = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: 1)
BIO_read(b, bp, Int32(size))
BIO_free(b)
let data = Data(bytes: bp, count: size)
The above code converts an OpenSSL X509_REQ
object into a DER
using the OpenSSL method i2d_X509_REQ_bio
.上面的代码使用 OpenSSL 方法
i2d_X509_REQ_bio
将 OpenSSL X509_REQ
对象转换为DER
。 The problem I'm having is the BIO_read
command and the UnsafeMutablePointer
storage object both need a size count for the number of bytes.我遇到的问题是
BIO_read
命令和UnsafeMutablePointer
存储对象都需要字节数的大小计数。 Does anybody know the correct way to get the length of bytes of an object pointed to by a UnsafeMutablePointer<Any>
in Swift?有人知道在 Swift 中
UnsafeMutablePointer<Any>
指向的对象的字节长度的正确方法吗? (I'm hard-coding an arbitrary number right now, 3000, which is very bad) The X509_Req
object doesn't have any size
or count
helper methods on it, and digging into Apple's documentation I'm not seeing a clear way to find the length of an object at a pointer. (我现在正在硬编码一个任意数字,3000,这是非常糟糕的)
X509_Req
对象上没有任何size
或count
辅助方法,并且深入研究 Apple 的文档我没有看到明确的方法在指针处找到对象的长度。
A pointer is just a memory address, without any information of the size of the memory region that it points to.指针只是一个内存地址,没有它指向的内存区域大小的任何信息。
However – if I understand the task correctly – what you actually need is the amount of bytes written to the memory-based BIO.但是——如果我理解正确的话——你真正需要的是写入基于内存的 BIO 的字节数。 That's what
BIO_get_mem_data
is for.这就是
BIO_get_mem_data
的用途。 Unfortunately, the OpenSSL library implements that as a macro不幸的是,OpenSSL 库将其实现为宏
# define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)pp)
which is not imported into Swift, so that you have to call BIO_ctrl
directly.它没有导入到 Swift 中,因此您必须直接调用
BIO_ctrl
。
Example (error checking omitted for brevity):示例(为简洁起见省略了错误检查):
// Create memory-based BIO:
let membio = BIO_new(BIO_s_mem())
// Write to BIO:
let status = i2d_X509_REQ_bio(membio, x509_REQ)
// Get pointer to the start of the memory BIOs data
// and amount of data available:
var ptr: UnsafeMutableRawPointer?
let len = BIO_ctrl(membio, BIO_CTRL_INFO, 0, &ptr)
// Create `Data` object from that memory region:
let data = Data(bytes: ptr!, count: len)
// Release BIO:
BIO_vfree(membio)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.