问题
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