From []byte to char*

一世执手 提交于 2021-02-06 10:16:50

问题


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:


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



来源:https://stackoverflow.com/questions/16375997/from-byte-to-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!