How to change []byte to char *?

golang code:

str := "mycgomain1111"
bytestr := []byte(str)
C.output((*C.char)(unsafe.Pointer(&bytestr1[0])))

C code:
void output(char * str)
{
int len=strlen(str);
printf("%s,len=%d,last=%d\n",str,len,str[len]);
}

When I change sting to []byte , and then change []byte to pointer char * ,
should I need to append '\x00' in the last []byte ?

I have do some test , if i don’t append ,it work well ! I want to know why ?
I am worried that it will make access wrong memery address!

Could you help me ? Please !

Looks like you are trying to convert a go string into a c string. cgo provides a function to do that:

// Go string to C string
// The C string is allocated in the C heap using malloc.
// It is the caller's responsibility to arrange for it to be
// freed, such as by calling C.free (be sure to include stdlib.h
// if C.free is needed).
func C.CString(string) *C.char

The problem you encountered after append is because append will create a new underlying array if the current underlying array does not have enough capacity for the appended data. The garbage collector is then free to collect the old underlying array, making the pointer you gathered with unsafe no longer valid.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.