CGO String Conversions šŸŽÆ

beginner
18 min

CGO String Conversions šŸŽÆ

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! šŸ“

What are String Conversions?

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).

Go Strings (string type) šŸ’”

Go strings are sequences of bytes representing text. They are declared as follows:

go
myString := "Hello, World!"

C Strings (*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.

c
char* myCString = "Hello, World!";

Converting Go Strings to C Strings

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.

go
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 C Strings to Go Strings

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.

go
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) }

Putting it all together

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.

go
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!ā¤ļø
Quick Quiz
Question 1 of 1

What does the `C.CString` function do in Go?

Quick Quiz
Question 1 of 1

Why do we need to deallocate memory when using `C.CString` in Go?