I'm working with this C struct on a 64 bit platform, trying to access the ui32v field in the value union:
struct _GNetSnmpVarBind {
guint32 *oid; /* name of the variable */
gsize oid_len; /* length of the name */
GNetSnmpVarBindType type; /* variable type / exception */
union {
gint32 i32; /* 32 bit signed */
guint32 ui32; /* 32 bit unsigned */
gint64 i64; /* 64 bit signed */
guint64 ui64; /* 64 bit unsigned */
guint8 *ui8v; /* 8 bit unsigned vector */
guint32 *ui32v; /* 32 bit unsigned vector */
} value; /* value of the variable */
gsize value_len; /* length of a vector in bytes */
};
I could write a C wrapper function for each union element but for didactic purposes I'd rather work in Go. Here's how I'm trying to access the ui32v field:
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 {
return (*_Ctype_guint32)(unsafe.Pointer(ptr))
}
return nil
}
However this gives an error cannot convert ptr (type uint64) to type unsafe.Pointer
So how do I convert a uint64 to a Go type that points to a C guint32? I've tried various combinations of casting to a uintptr then casting to a *_Ctype_guint32, casting to a uintptr then using unsafe.Pointer, ...
My reasoning is: I'm passed an array of 8 bytes. Convert that to a uint64, that's the memory address. Cast that to a pointer to a guint32 (ie a C array of guint32's), and return that as a result - that is the union field "value" as a guint32 *.
Context
Later I'll want to convert the C array of guint32's to a string utilising the value_len field, using a function I know already works:
guint32_star := union_to_guint32_ptr(data.value)
result += OidArrayToString(guint32_star, data.value_len)
The C code is from gsnmp.