Accessing a C Array of Type const char * from Go
Problem
A C program defines an array of type const char *, named myStringArray, containing a list of strings. The goal is to access this array from a Go program using cgo and convert each array entry into a Go string.
Discussion
However, the provided Go code fails to access the array correctly, instead it iterates over the characters of the first string in the array.
Solution
A better approach is to first convert the C array into a Go slice, which provides a more convenient and safer way to access its elements. Here's how this can be done:
import "C" import "fmt" // Convert the C array into a Go slice of pointers to C (null-terminated) strings. arraySize := 3 cStrings := (*[1 << 30]*C.char)(unsafe.Pointer(&C.myStringArray))[:arraySize:arraySize] // Iterate over the slice and convert each C string into a Go string. for _, cString := range cStrings { fmt.Println(C.GoString(cString)) }
Output:
NAME_OF_FIRST_THING NAME_OF_SECOND_THING NAME_OF_THIRD_THING
This solution ensures that each array element is accessed correctly as a distinct Go string.
The above is the detailed content of How to Access a C `const char*` Array from Go?. For more information, please follow other related articles on the PHP Chinese website!