When calling a C function that expects a pointer to a pointer to an array of strings, how can this be achieved in Go while also allowing the C function to modify the string array?
Creating a slice in Go and passing it directly to a C function is not possible due to differences in data structures and memory allocation. Instead, it is necessary to allocate the array in C.
// Allocate an array in C cArray := C.malloc(C.size_t(c_count) * C.size_t(unsafe.Sizeof(uintptr(0)))) // Convert C array to Go array a := (*[1<<30 - 1]*C.char)(cArray) // Copy Go strings to C array for index, value := range strs { a[index] = C.CString(value) } // Call C function with pointer to array pointer err := C.f(&c_count, (***C.char)(unsafe.Pointer(&cArray)))
By allocating the array in C, it allows the C function to modify and resize the array. The changes made in C will be reflected in the Go slice after the C function returns.
The above is the detailed content of How to Pass a Go Slice to a C Function that Modifies a Pointer to a Pointer to an Array of Strings?. For more information, please follow other related articles on the PHP Chinese website!