How to change []byte to char *?

golang code:

str := "mycgomain1111"
bytestr := []byte(str)

C code:
void output(char * str)
int len=strlen(str);

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 (be sure to include stdlib.h
// if 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.