swift - 从类型的字符串中确定类型以快速读取二进制数据
问题描述
我有从 C++ 应用程序写入的 TB 二进制数据、带有坐标和 4 个浮点数的稀疏数据。我现在正在快速编写一个应用程序来读取该数据。二进制数据是重复的,例如UInt8, UInt8, Float32, Float32, Float32, Float32...
。大约 12 个月前编写数据时,我包含了一个单独的 json 文件来描述数据。我现在需要使用 Type 的那些 String 表示来快速调用一个函数来读取二进制文件。
//A string representation of the type of binary data stored on disk
struct dimJSON{
let diskColRowType: String = "UInt8"
let diskQType: String = "Float32"
var sizeColRowTypeInBytes:Int {
if diskColRowType = "UInt8" {return 1}
...etc
}
//The function used to read the data
func readBinaryData<diskColRow: BinaryInteger, diskQ: BinaryFloatingPoint>(diskColRow: diskColRow.Type, diskQ: diskQ.Type) -> [[[diskQ]]]{
var plane = [[[diskQ]]]()
data.withUnsafeBytes{ (ptr: UnsafeRawBufferPointer) in
for index in stride(from: 0, to: dim.binFileSizeInStructs * dim.sizeStructInBytes, by: dim.sizeStructInBytes) {
let col = Int(ptr.load(fromByteOffset: index, as: diskColRow.self))
let row = Int(ptr.load(fromByteOffset: index + dim.sizeColRowTypeInBytes, as: diskColRow.self))
//Cannot ptr.load bytes offset, due to possible unaligned memory
let q = Data(bytes: ptr.baseAddress!.advanced(by: index + dim.byteOffsetQVec), count: 4 * dim.sizeQTypeInBytes)
plane[col][row] = q.toArray(type: diskQ.self)
}
}
return plane
}
//This works, but seems dull, and I have multiple call sites for similar funcs readBinaryData.
if dim.diskColRowType == "UInt8" && dim.diskQ == "Float32"{
let p = readBinaryData(diskColRow: UInt8.self, diskQ: Float32.self)
} else if dim.diskColRowType == "UInt16" && dim.diskQ == "Double" {
let p = readBinaryData(diskColRow: UInt16.self, diskQ: Double.self)
}
//Something like this would be good:
extension dimJSON {
func getType() -> ?????? {
if diskColRowType = "UInt8" {return UInt8.self}
else if diskColRowType = "UInt16" {return UInt16.self}
...
}
}
解决方案
推荐阅读
- javascript - 在 AWS lambda 函数中使用个人需求的优势
- python-3.x - Pytest 在某个线程中运行某个测试套件
- android - Android Studio - Android 模拟器以不同的方式呈现布局。模拟器运行程序时高度似乎较小
- ios - Apple TV 第 4 代中的 Powerpoint
- java - 根据长度乘以数字
- ios - 单击图像时如何添加操作?
- c# - 如何将 Localhost(网站)连接到 UWP 应用程序?
- sql - 评估多个列并返回与值条件匹配的列的 SQL 案例语句?
- python - 从 Python 获取参数的类中调用方法具有意外类型
- c# - 在 VFP 中完成 dll 的 WCF 中的 com 引用出错