CodeBlanks Logo Icon CodeBlanks

Summary - cgo

Combine cgo to call a C math function.

cgo summary

In this group you called C code with import "C" and the preamble, linked libraries with #cgo, converted C.int/C.double, moved text with C.CString/C.GoString and released memory with C.free.

Remember: cgo calls are expensive and complicate cross-compiling; prefer a pure-Go alternative when one exists.

A complete example

Processing a Go string in a C function and getting the result back:

/*
#include <ctype.h>
void buyut(char* s) { for (; *s; s++) *s = toupper(*s); }
*/
import "C"

cs := C.CString("go")
defer C.free(unsafe.Pointer(cs))
C.buyut(cs)
fmt.Println(C.GoString(cs))  // GO

Practice Convert to upper case

Add stdlib.h and ctype.h in the preamble and write void buyut(char* s) using toupper. Create a C.CString for "gopher", set up freeing, call C.buyut and print with C.GoString.

Starter code

main.go
package main

/*
// C kodu buraya
*/
import "C"

import (
    "fmt"
    "unsafe"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

/*
#include <stdlib.h>
#include <ctype.h>
void buyut(char* s) { for (; *s; s++) *s = toupper(*s); }
*/
import "C"

import (
    "fmt"
    "unsafe"
)

func main() {
    cs := C.CString("gopher")
    defer C.free(unsafe.Pointer(cs))
    C.buyut(cs)
    fmt.Println(C.GoString(cs))
}

Expected output

GOPHER

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which allocates C memory and requires <code>C.free</code>?

  • C.int(5)
  • float64(C.f())
  • C.CString("x") Correct answer
  • C.GoString(p)

Explanation: C.CString makes a copy with malloc; the others either produce Go memory or are just type conversions.

2 Disable cgo

Question
GOOS=linux ____=0 go build -o app .
Answer
GOOS=linux CGO_ENABLED=0 go build -o app .

Explanation: CGO_ENABLED=0 builds pure Go; it is used for cross-compiling and static binaries.

3 Group summary

Term Meaning
import "C" Gateway to C
#cgo LDFLAGS Linking a library
C.CString / C.GoString Moving text
C.free Releasing memory

All lessons in Advanced