从[]个字节到char * [英] From []byte to char*

查看:42
本文介绍了从[]个字节到char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包装一个C函数,该函数采用 char * 指向字节的非空缓冲区(的第一个元素).我正在尝试使用CGo将其包装在Go函数中,以便可以将其传递给 [] byte ,但我不知道如何进行转换.C函数签名的简化版本是

I want to wrap a C function that takes a char* pointing to (the first element of) a non-empty buffer of bytes. I'm trying to wrap that in a Go function using CGo so that I can pass it a []byte, but I don't know how to do the conversion. A simplified version of the C function's signature is

void foo(char const *buf, size_t n);

我尝试使用

C.foo(&b[0], C.size_t(n))

尽管如此,它仍无法编译:

That doesn't compile, though:

cannot use &b[0] (type *byte) as type *_Ctype_char in function argument

那么这里正确的程序是什么? go-wiki 仅描述相反的情况.

So what's the correct procedure here? The go-wiki only describes the reverse situation.

推荐答案

好吧,事实证明这比我想象的要容易得多:

Ok, that turned out to be much easier than I thought:

(*C.char)(unsafe.Pointer(&b[0]))

可以解决问题.(可通过 golang-nuts 找到.)

does the trick. (Found this at golang-nuts.)

这篇关于从[]个字节到char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆