从[]byte到char*

huangapple go评论75阅读模式
英文:

From []byte to char*

问题

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

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

我尝试使用以下方式将切片中的第一个byte的指针传递给它:

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

然而,这样不能编译通过:

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

那么正确的步骤是什么呢?go-wiki只描述了相反的情况。

英文:

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);

I tried passing a pointer to the first byte in the slice with

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

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

答案1

得分: 29

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

英文:

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

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

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

huangapple
  • 本文由 发表于 2013年5月4日 23:37:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/16375997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定