Golang CGo: converting union field to Go type

后端 未结 4 1626
深忆病人
深忆病人 2021-01-12 04:55

I\'m working with this C struct on a 64 bit platform, trying to access the ui32v field in the value union:

struct _GNetSnmp         


        
4条回答
  •  礼貌的吻别
    2021-01-12 05:37

    The solution was first to cast to uintptr, then cast to unsafe.Pointer ie two separate casts:

    func union_to_guint32_ptr(cbytes [8]byte) (result *_Ctype_guint32) {
        buf := bytes.NewBuffer(cbytes[:])
        var ptr uint64
        if err := binary.Read(buf, binary.LittleEndian, &ptr); err == nil {
            uptr := uintptr(ptr)
            return (*_Ctype_guint32)(unsafe.Pointer(uptr))
        }   
        return nil 
    }                
    

    I checked this by comparing results with a command line tool, and it's returning correct results.


    Context

    // gsnmp._Ctype_gpointer -> *gsnmp._Ctype_GNetSnmpVarBind
    data := (*C.GNetSnmpVarBind)(out.data)
    
    switch VarBindType(data._type) {
    case GNET_SNMP_VARBIND_TYPE_OBJECTID:
        result += "GNET_SNMP_VARBIND_TYPE_OBJECTID" + ":"
        guint32_star := union_to_guint32_ptr(data.value)
        result += OidArrayToString(guint32_star, data.value_len)
    

提交回复
热议问题