duandanai6470 2013-02-12 05:53
浏览 882

Go / CGo-如何使用作为指针传递的C数组

I'm posting this as a question/answer, as it took me a while to work out, and I wouldn't mind some feedback on my solution. In Go/CGo, how do you work with a C array passed as a pointer?

For example, with this C struct:

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

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

  • 写回答

3条回答 默认 最新

  • douzhi2012 2013-02-12 05:53
    关注

    The way I did it was to find the number of bytes to be read (size of a guint32 * oid_len), then did a binary.Read() on the number of bytes, then looped through be bytes in chunks of size. Easy in retrospect; the hard part was getting the type conversions working as Go is stricter than C.

    For example here's the Go code for converting the guint32* to a Go string (representing an SNMP OID):

    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>"
    }
    

    Comments?


    Context: the code is from gsnmpgo.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘