Welcome back to CodeYourCraft! Today, we're diving into the exciting world of CGO Types in Golang. Let's get started!
CGO, or C Go Interface, allows us to call C functions and use C libraries in our Go programs. In this lesson, we'll explore various CGO types that are essential for using C libraries in Go.
Before we dive into the details, let's familiarize ourselves with some basic CGO types:
C.char: equivalent to Go's byteC.int, C.long, C.short, C.long long: equivalent to Go's int32, int64, int16, int64 respectivelyC.uint, C.unsigned long, C.unsigned short, C.unsigned long long: equivalent to Go's uint32, uint64, uint16, uint64 respectivelyC.float, C.double, C.long double: equivalent to Go's float32, float64, and math.Float64 respectivelyC.ptrDiff_t: equivalent to Go's int for pointer arithmeticIn C, pointers play a significant role. To declare a pointer in Go using CGO, we use the **type** syntax. Here's an example:
package main
/*import C.stdlib*/
import "C"
func main() {
var p *C.char // Declare a pointer to char type
p = C.CString("Hello, World!") // Initialize the pointer
defer C.free(unsafe.Pointer(p)) // Free the memory when done
C.printf("%s\n", p) // Print the string
}In this example, we declare a pointer to char type, initialize it with a string, and free the memory when we're done using the defer keyword.
Working with structs in CGO is straightforward. Here's a simple example:
package main
import "C"
// Define a Go struct
type Person struct {
Name *C.char
Age C.int
}
// Define a C struct
const GoPerson = "__Go_PERSON"
// C function to create a Person struct
extern C.void GoPersonCreate(**C.struct_Person)
// C struct definition
type struct_Person C.struct_t
func main() {
person := &Person{
Name: C.CString("John Doe"),
Age: 30,
}
// Call the C function to create a C struct
var cPerson C.struct_Person
GoPersonCreate(unsafe.Pointer(&cPerson))
// Fill the C struct with our Go Person struct data
cPerson.f0 = unsafe.Pointer(person.Name)
cPerson.f1 = (*C.int)(unsafe.Pointer(&person.Age))
// Now you can use the C struct as needed with C functions
}In this example, we define a Go struct Person, a C struct struct_Person, and a C function GoPersonCreate to create a C struct. We then create a Go Person, call the C function to create a C struct, and fill the C struct with our Go Person data.
What is the purpose of the `C.CString` function in the example?
That's it for today! In the next lesson, we'll explore more advanced CGO concepts and see how to call C functions and use C libraries in our Go programs.
Stay tuned and happy coding! 💻💞