Go / CGo - how do you use a C array passed as a pointer

I am posting this as a question / answer, since it took me a while to figure it out, and I would not mind some feedback on my decision. In Go / CGo, how do you work with a C array passed as a pointer?

For example, using this C structure:

struct _GNetSnmpVarBind {                     
    guint32     *oid;       /* name of the variable */
    gsize       oid_len;    /* length of the name */
    ... and other fields
};  

I want to convert the oid field to a Go string, how would I work with the guint32 * pointer?

+6
source share
3 answers

The way I did this was to find the number of bytes to read (size guint32 * oid_len), then made a binary .Read () by the number of bytes, and then looped through the bytes in chunks of size, Easy in retrospect; the hard part got type conversions that worked like Go, more stringent than C.

, Go guint32 * Go ( OID SNMP):

func gIntArrayOidString(oid *_Ctype_guint32, oid_len _Ctype_gsize) (result string) {
    size := int(unsafe.Sizeof(*oid))
    length := int(oid_len)
    gbytes := C.GoBytes(unsafe.Pointer(oid), (_Ctype_int)(size*length))
    buf := bytes.NewBuffer(gbytes)

    for i := 0; i < length; i++ {
        var out uint32
        if err := binary.Read(buf, binary.LittleEndian, &out); err == nil {
            result += fmt.Sprintf(".%d", out)
        } else {
            return "<error converting oid>"
        }
    }
    if len(result) > 1 {
        return result[1:] // strip leading dot
    }
    return "<error converting oid>"
}

?


: gsnmpgo.

+4

C Go, , go wiki

, , , ! , C, .

, , , .

func gIntArrayOidString(oid *_Ctype_guint32, oid_len _Ctype_gsize) (result string) {
    var oids []uint32
    sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&oids)))
    sliceHeader.Cap = oid_len
    sliceHeader.Len = oid_len
    sliceHeader.Data = uintptr(unsafe.Pointer(oid))

    var result string
    for _, value := range oids {
        result += fmt.Sprintf(".%d", value)
    }
    return result[1:]
}
+3

I assume that the values ​​from gsnmp are not necessarily in little-endian, but in native byte order. I would just use unsafe.Sizeof to iterate through the array. eg.

package main

import (
    "unsafe"
    "fmt"
)

var ints = [...]int32 {1, 2, 3}

func main() {
    var result string
    var p *int32 = &ints[0]
    for i := 0; i < len(ints); i++ {
        result += fmt.Sprintf(".%d", *p)
        p = (*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(p))+unsafe.Sizeof(*p)))
    }
    fmt.Println(result[1:])
}
+2
source

All Articles