doujia9833 2014-04-11 05:49
浏览 62
已采纳

将C结构转换为Go结构的好方法或推荐方法

i'm using cgo for developing library binding from Go. Let me consider the C struct and Go Struct as below.

struct cons_t {
  size_t type;
  cons_t *car;
  cons_t *cdr;
};

cons_t* parse(const char *str);

and this is go's struct

type Cons struct {
  type int;
  car *Cons;
  cdr *Cons;
}

For implementing Go function as below, what is better way to implement TranslateCCons2GoCons?

func Parse (str string) *Cons {
  str_ptr := C.CString(string);
  cons_ptr := C.parse(str_ptr);
  retCons := TranslateCCons2GoCons(cons_ptr);
  return retCons;
}

My first answer is as below.

/*#cgo
int getType(cons_t *cons) {
    return cons->type;
}
cons_t *getCar(cons_t *cons) {
  return cons->car;
}
cons_t *getCdr(cons_t *cons) {
  return cons->cdr;
}
*/

func TranslateCCons2GoCons (c *C.cons_t) Cons {
  type := C.getType(c);
  car := C.getCar(c);
  cdr := C.getCdr(c);
  // drop null termination for simplicity
  return Cons{type, TranslateCCons2GoCons(car), TranslateCCons2GoCons(cdr)};
}

are there any better way?

  • 写回答

2条回答 默认 最新

  • duanben1324 2014-04-11 06:02
    关注

    I would recommend against the accessor functions. You should be able to access the fields of the C struct directly, which will avoid the Go -> C function call overhead (which is non-trivial). So you might use something like:

    func TranslateCCons2GoCons (c *C.cons_t) *Cons {
        if c == nil {
            return nil
        }
        return &Cons{
            type: int(c.type),
            car: TranslateCCons2GoCons(c.car),
            cdr: TranslateCCons2GoCons(c.cdr),
        }
    }
    

    Also, if you allocate a C string with C.CString, you need to free it. So your Parse function should look something like:

    func Parse (str string) *Cons {
        str_ptr := C.CString(str)
        defer C.free(unsafe.Pointer(str_ptr)
        cons_ptr := C.parse(str_ptr)
        retCons := TranslateCCons2GoCons(cons_ptr)
        // FIXME: Do something to free cons_ptr here.  The Go runtime won't do it for you
        return retCons
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)