CodeBlanks Logo Icon CodeBlanks

Go-C conversion

Learn conversion between Go string and C.CString.

String conversion

Go strings carry their length, while C strings end with \0. C.CString(s) copies a Go string into C memory; C.GoString(p) turns a *C.char into a Go string.

cs := C.CString("merhaba")
defer C.free(unsafe.Pointer(cs))
fmt.Println(C.strlen(cs))  // 7

Byte slices

For byte data, C.CBytes(b) copies a []byte into C memory and C.GoBytes(p, n) copies n bytes from C memory into a Go slice. All these conversions copy; with large data their cost matters.

Practice String length

Add #include <stdlib.h> and #include <string.h> in the preamble. Create a C.CString for "gopher", free it with defer C.free(unsafe.Pointer(cs)) and print C.strlen(cs).

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 <string.h>
*/
import "C"

import (
    "fmt"
    "unsafe"
)

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

Expected output

6

Questions and answers

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

1 Who frees the memory allocated by <code>C.CString</code>?

  • You, with C.free Correct answer
  • The Go garbage collector
  • It is freed automatically on exit only
  • The C.GoString call

Explanation: C.CString allocates C memory with malloc; the GC can't see it, so it leaks unless freed with C.free.

2 Convert a C string to Go

Question
p := C.CString("go")
s := C.____(p)
Answer
p := C.CString("go")
s := C.GoString(p)

Explanation: C.GoString copies a *C.char into a Go string.

3 Conversion functions

Term Meaning
C.CString Go → C string
C.GoString C → Go string
C.CBytes Go → C bytes
C.GoBytes C → Go bytes

All lessons in Advanced