将Go字符串转换为不带CGo的C字符串
我试图从Go调用一些ioctl,其中一些以C字符串作为参数。例如,在C中:将Go字符串转换为不带CGo的C字符串,go,c-strings,unsafe,cgo,Go,C Strings,Unsafe,Cgo,我试图从Go调用一些ioctl,其中一些以C字符串作为参数。例如,在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_
/* 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;
}
现在,如何将Go字符串
转换为存储在不安全指针
中的C字符串?我不想使用CGo,因为我在交叉编译,这会让事情变得很痛苦。啊找到了答案(反正是编译的东西)。首先强制转换为[]字节
,然后获取第一个元素的地址:
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
}
啊找到了答案(反正是编译出来的东西)。首先强制转换为[]字节
,然后获取第一个元素的地址:
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
}
人们通常会将
名称
字段设置为*字节
,而不是不安全的指针
。在syscall包中查找示例,例如:啊,是的,这更有意义!人们通常会将名称
字段设置为*字节
,而不是不安全的指针
。在syscall包中查找示例,例如:啊,是的,这更有意义!