我正在編寫將字節流反序列化為對象的代碼,我一直在獲取結構字段的指針?;旧洗a的工作方式如下:它獲取指向結構的指針,然后根據它序列化它的類型,例如。如果它是一個整數,它需要接下來的 4 個字節。棘手的情況是,如果它是一個結構,因為我必須對其所有屬性遞歸運行反序列化,而且我不知道如何獲取其字段的地址以將它們傳遞給反序列化。func Deserialize(objPtr interface{}, b []byte) (bytesRead int) { // it should be the address of the object val := reflect.ValueOf(objPtr).Elem() valPtr := reflect.ValueOf(objPtr) // check if either the object or *object is Serializable _, isSerializable := (val.Interface()).(Serializable) _, bo := (valPtr.Interface()).(Serializable) isSerializable = isSerializable || bo // specific type serialization if isSerializable{ return objPtr.(Serializable).Deserializebyte(b) } switch val.Kind() { case reflect.Uint32, reflect.Int, reflect.Int32: res := reflect.ValueOf(binary.LittleEndian.Uint32(b[:4])) valPtr.Set(res) return 4 case reflect.Uint64, reflect.Int64: res := reflect.ValueOf(binary.LittleEndian.Uint32(b[:8])) valPtr.Set(res) return 8 case reflect.Struct: n_bytes := 0 for i := 0; i < val.NumField(); i++ { // stuck in here valPtr.Elem() // I don't think the next line works last_n_bytes := Deserialize(&(valPtr.Elem().Field(i).Interface()), b) n_bytes += last_n_bytes b = b[last_n_bytes:] } //valPtr.Set(res) return n_bytes default: panic("this panic is for debug, every case should be handled above") res := val.Bytes() valPtr.Set(res) return len(val.Bytes()) } return 0}
1 回答

夢里花落0921
TA貢獻1772條經驗 獲得超6個贊
使用 reflect API 獲取字段的地址:
last_n_bytes?:=?Deserialize(valPtr.Elem().Field(i).Addr().Interface(),?b)
該superint
示例發生錯誤,因為應用程序通過反射 API 獲取了未導出字段的地址。這是不允許的,因為它會允許另一個包修改該字段。
這是一個導出字段的工作示例:
type superint struct {
? ? A int
? ? B int
}
func (s *superint) lol() {}
type a interface{ lol() }
func main() {
? ? i := superint{A: 1, B: 9}
? ? valPtr := reflect.ValueOf(&i)
? ? fmt.Printf("%v \n", &i.A)
? ? fmt.Printf("%v \n", valPtr.Elem().Field(0).Addr().Interface())
}
- 1 回答
- 0 關注
- 167 瀏覽
添加回答
舉報
0/150
提交
取消