我想将c ++结构定义为swift代码,并将其序列化和反序列化以写入套接字。
class PacketHeader: NSObject, NSCoding {
var ver: UInt8 = 0
var len: UInt32 = 0
required init(coder aDecoder: NSCoder) {
??
}
func encode(with aCoder: NSCoder) {
??
}
}
我找不到解码和编码uint8,uint32的函数。
答案 0 :(得分:1)
如果您不想转换为NSNumber
,则需要执行以下操作,但我怀疑这必须是一个重复的问题:
class PacketHeader: NSObject, NSCoding {
var ver: UInt8 = 0
var len: UInt32 = 0
init(ver: UInt8, len: UInt32) {
self.ver = ver
self.len = len
super.init()
}
required init(coder aDecoder: NSCoder) {
self.ver = UInt8(aDecoder.decodeCInt(forKey: "ver"))
self.len = UInt32(aDecoder.decodeCInt(forKey: "len"))
}
func encode(with aCoder: NSCoder) {
aCoder.encodeCInt(Int32(self.ver), forKey: "ver")
aCoder.encodeCInt(Int32(self.len), forKey: "len")
}
}
let x = PacketHeader(ver: 75, len: 123)
let e = NSKeyedArchiver.archivedData(withRootObject: x)
if let y = NSKeyedUnarchiver.unarchiveObject(with: e) as? PacketHeader {
print("\(y.ver), \(y.len)") // 75, 123
} else {
print("URK???")
}
答案 1 :(得分:1)
Xcode 8(Swift 3)游乐场:
class PacketHeader: NSObject, NSCoding {
var ver: UInt8 = 0
var len: UInt32 = 0
override init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
if let ver = aDecoder.decodeObject(forKey: "ver") as? NSNumber {
self.ver = ver.uint8Value
}
if let len = aDecoder.decodeObject(forKey: "len") as? NSNumber {
self.len = len.uint32Value
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(NSNumber(value: ver), forKey: "ver")
aCoder.encode(NSNumber(value: len), forKey: "len")
}
}
let data = PacketHeader()
data.ver = 10
data.len = 8
let savedData = NSKeyedArchiver.archivedData(withRootObject: data)
let obj = NSKeyedUnarchiver.unarchiveObject(with: savedData) as? PacketHeader
obj?.ver
obj?.len