doqs8936 2016-08-02 17:14
浏览 181

不使用CGo将Go字符串转换为C字符串

I'm trying to call some ioctls from Go, and some of them take C strings as parameters. For example, in C:

/* When the user asks to bind a message name to an interface, they use: */
struct kbus_bind_request {
    __u32 is_replier;   /* are we a replier? */
    __u32 name_len;
    char *name;
};

extern int kbus_ksock_bind(kbus_ksock_t         ksock,
                           const char          *name,
                           uint32_t             is_replier)
{
  int   rv;
  kbus_bind_request_t   bind_request;

  bind_request.name = (char *) name;
  bind_request.name_len = strlen(name);
  bind_request.is_replier = is_replier;

  rv = ioctl(ksock, KBUS_IOC_BIND, &bind_request);
  if (rv < 0)
    return -errno;
  else
    return rv;
}

I converted the struct to a Go struc like this:

type kbus_bind_request struct {
    is_replier uint32 /* are we a replier? */
    name_len   uint32
    name       unsafe.Pointer // char*
}

Now, how do I convert a Go string to a C string stored in an unsafe.Pointer? I don't want to use CGo as I am cross-compiling and it makes things a pain.

  • 写回答

1条回答 默认 最新

  • douwojiao5919 2016-08-02 17:17
    关注

    Ah found the answer (well something that compiles anyway). First cast to []byte, then take the address of the first element:

    func int_bind(ksock int, name string, is_replier uint32) int {
    
        bind_request := &kbus_bind_request{}
    
        s := []byte(name)
    
        bind_request.name = unsafe.Pointer(&s[0])
        bind_request.name_len = uint32(len(s))
        bind_request.is_replier = is_replier
    
        rv := ioctl(ksock, KBUS_IOC_BIND, unsafe.Pointer(bind_request))
    
        if rv != 0 {
            return -int(rv)
        }
        return 0
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献