How to convert a null-terminated byte array (C-string) to a string in Go?
Hello everyone! I'm new to Go and writing a program that interacts with C code via cgo. In the C part, I receive a null-terminated string (`\0`) as `*C.char`. I'm trying to convert it to a regular Go string, but I'm running into issues.
For example, I have a function that returns `*C.char`:
```go
// char* get_name(void);
import "C"
func getName() string {
name := C.get_name()
// How to properly convert name to a Go string?
}
```
I've tried using `C.GoString(name)`, but I'm not sure if this is correct for all cases. What if the byte array contains null bytes inside? Or if the string is very long? How to avoid memory leaks and panics?
Please advise the correct way to convert a null-terminated byte array to a Go string.
No answers yet.
Log in to leave an answer