duanba7498 2012-03-17 07:32
浏览 15
已采纳

使用反射将字节读入结构

I'm trying to write functions that will allow me to marshal/unmarshal simple structs into byte arrays. I've succeeded in writing Marshal, with help from the kind folks at #go-nuts, but I'm running into trouble writing Unmarshal.

// Unmarshal unpacks the binary data and stores it in the packet using
// reflection.
func Unmarshal(b []byte, t reflect.Type) (pkt interface{}, err error) {
    buf := bytes.NewBuffer(b)
    p := reflect.New(t)
    v := reflect.ValueOf(p)
    for i := 0; i < t.NumField(); i++ {
        f := v.Field(i)
        switch f.Kind() {
        case reflect.String:
            // length of string
            var l int16
            var e error
            e = binary.Read(buf, binary.BigEndian, &l)
            if e != nil {
                err = e
                return
            }

            // read length-of-string bytes from the buffer
            raw := make([]byte, l)
            _, e = buf.Read(raw)
            if e != nil {
                err = e
                return
            }

            // convert the bytes to a string
            f.SetString(bytes.NewBuffer(raw).String())
        default:
            e := binary.Read(buf, binary.BigEndian, f.Addr())
            if e != nil {
                err = e
                return
            }
        }
    }

    pkt = p
    return
}

The problem with the code above is that the call to f.Addr() near the end is apparently trying to get the address of an unaddressable value.

If there is an alternative solution, I would appreciate that as well. Either way, any help would be much appreciated.

Thanks!

  • 写回答

3条回答 默认 最新

  • doujue6196 2012-03-17 09:55
    关注

    I think you should use

    v := p.Elem()   // Get the value that 'p' points to
    

    instead of

    v := reflect.ValueOf(p)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据