Welcome to our deep dive into Golang (Go) and its powerful CGO (C Go) package! Today, we're focusing on a crucial aspect: String Conversions. By the end of this lesson, you'll be comfortable with converting Go strings to C strings and vice versa.
Let's get started! š
In programming, string conversions refer to the process of transforming a string from one data type to another. For Go and CGO, we're primarily interested in converting between Go strings (string type) and C strings (*C.char type).
string type) š”Go strings are sequences of bytes representing text. They are declared as follows:
myString := "Hello, World!"*C.char type) š”C strings are null-terminated arrays of bytes, where the final byte is a \0 (ASCII NUL) character. CGO allows us to work with C strings in Go.
char* myCString = "Hello, World!";To convert a Go string to a C string, we use the C.CString function from the unsafe package. This function returns a pointer to a newly allocated C string.
package main
import "C"
import "unsafe"
func main() {
myGoString := "Hello, World!"
myCString := C.CString(myGoString)
defer C.free(unsafe.Pointer(myCString))
// myCString is now a valid C string
}š Note: Don't forget to deallocate the memory using C.free() to avoid memory leaks!
Converting a C string to a Go string is simpler, as Go provides a built-in function called string(). This function returns a Go string from a slice of bytes.
package main
import "C"
import "fmt"
func main() {
charPtr := C.CString("Hello, World!")
defer C.free(unsafe.Pointer(charPtr))
myGoString := C.GoString(charPtr)
fmt.Println(myGoString)
}Let's create a simple example that converts a Go string to a C string, modifies it, and then converts it back to a Go string.
package main
import "C"
import "fmt"
import "unsafe"
func main() {
myGoString := "Hello, World!"
myCString := C.CString(myGoString)
defer C.free(unsafe.Pointer(myCString))
// Modify the C string
C.(*C.char)(unsafe.Pointer(myCString))[len(myGoString)-4:] = []byte("!ā¤ļø")
modifiedMyCString := C.GoString(myCString)
fmt.Println(modifiedMyCString)
}Output:
Hello, World!ā¤ļø
What does the `C.CString` function do in Go?
Why do we need to deallocate memory when using `C.CString` in Go?