英文:
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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论