dongzizhi9903 2015-05-17 13:12
浏览 34
已采纳

在go lang中强制转换为结构类型

I have some c macros in the form of

#define VARATT_IS_4B(PTR) \
    ((((varattrib_1b *) (PTR))->va_header & 0x80) == 0x00)

and want to convert it to Go lang. I am doing something like

func varAttIs1B(ptr uintptr) bool {
    return (*varAttrib1b(ptr).vaHeader & 0x01) == 0x01
}

but yeah, it is not working and I am getting compiler error "cannot convert ptr (type int) to type varAttrib1b".

varAttrib1b is a struct with two fields and ptr is a uintptr(could be some other type also).

type varAttrib1b struct {
    vaHeader uint8
    vaData   []string
}

How can I do this?

  • 写回答

1条回答 默认 最新

  • doujianmin6527 2015-05-17 18:13
    关注

    You cannot cast pointers to arbitrary types in Go. If you really want to do that, you should use unsafe.Pointer:

    type varAttrib1b struct {
        vaHeader uint8
        vaData   []string
    }
    
    func varAttIs1B(ptr uintptr) bool {
        return ((*varAttrib1b)(unsafe.Pointer(ptr)).vaHeader & 0x01) == 0x01
    }
    

    It compiles and works, but are you sure there is no safe way of doing that in go? Can't you just define an interface:

    type Attr interface {
        AttrIs1B() bool
    }
    
    func (b varAttrib1b) AttrIs1B() bool {
        return b.vaHeader & 0x01 == 0x01
    }
    
    func varAttIs1B(attr Attr) bool {
        return attr.AttrIs1B()
    }
    

    Or implement it with type casts?

    func varAttIs1B(ptr interface{}) bool {
        switch a := ptr.(type) {
        case varAttrib1b:
            return a.vaHeader & 0x01 == 0x01
        }
        return false
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么