我有一个来自 HDF5 文件的浮点值 () 数组floatArray
,我想将此数据用作接受 Unsafe[Mutable]Pointer ( inputForFunction
) 的函数的输入。我是 UnsafePointer 的新手,所以我需要别人的帮助。
我想到的一种方法是将数组存储到文件中,然后打开它并将文件描述符映射到变量的内存以用于函数的输入:
// read the data from HDF5 file
var floatArray: [Float] = try originalHDF5DataSet.read()
// store the data
let dataToStore = NSData(bytes: &floatArray, length: sizeOfArray * MemoryLayout<Float>.size)
let tmpPath = URL(fileURLWithPath: NSTemporaryDirectory())
let filePath = tmpPath.appendingPathComponent("floatArrayData").appendingPathExtension("dat")
do{
try data.write(to: filePath, options: .atomic)
let fileManager : FileManager = FileManager.default
if fileManager.fileExists(atPath:filePath.path){
print("Success")
}else{
print("Fail")
}
// open the data
let dataPath = filePath.path
let fd = open(dataPath, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
assert(fd != -1, "Error: failed to open output file at \""+dataPath+"\" errno = \(errno)\n")
// memory map the parameters
let hdr = mmap(nil, Int(sizeOfArray), PROT_READ, MAP_FILE | MAP_SHARED, fd, 0)
// cast Void pointers to Float
let inputForFunction = UnsafePointer<Float>(hdr!.assumingMemoryBound(to: Float.self))
} catch{
print("failed")
}
但是,它可能不是最好的实现,因为存储数据的过程似乎很耗时。
这就是为什么我正在考虑使用 UnsafePointer 将指针从floatArray
to传递inputForFunction
,但我不确定如何实现它。仅供参考,我正在考虑的一种方法是withUnsafePointer
直接使用方法:
var floatArray: [Float] = try originalHDF5DataSet.read()
var inputForFunction = UnsafeMutablePointer<Float>.allocate(capacity: Int(sizeOfArray))
withUnsafePointer(to: &floatArray[0]) { (ptr: UnsafePointer<Float>) in
inputForFunction = UnsafeMutablePointer(mutating: ptr)
}
或者另一种方法是使用withMemoryRebound
(但以下方法不起作用):
var floatArray: [Float] = try originalHDF5DataSet.read()
var inputForFunction = UnsafeMutablePointer<Float>.allocate(capacity: Int(sizeOfArray))
withUnsafePointer(to: &floatArray) { (ptrDataArray: UnsafePointer<[Float]>) in
inputForFunction = ptrDataArray.withMemoryRebound(to: inputForFunction.self, capacity: Int(sizeOfArray), { (ptr: UnsafePointer<[Float]>) -> UnsafeMutablePointer<Float> in
return ptr[0]
})
}
我的问题是
- 如何将
floatArray
数据的地址传递给inputForFunction
? - 如果我需要从 UnsafePointer<[Float]> 转换为 Unsafe[Mutable]Pointer,该怎么做?
- 如果需要,如何
withMemoryRebound
用于此目的?我可以将地址/值分配给inputForFunction
闭包内部吗? - 当我检查 and 的地址时
floatArray
,floatArray[0]
它们是不同的(这似乎与 C/C++ 不同)。应该传递到哪个地址inputForFunction
?