How to Use unsafe.Pointer in Go

Use unsafe.Pointer to cast Go variable addresses for C function calls via cgo, ensuring the Go object remains referenced to prevent premature garbage collection.

Use unsafe.Pointer to convert between Go types and C pointers when calling C functions via cgo, bypassing type safety for direct memory access. You must import the unsafe package and cast the address of a Go variable to unsafe.Pointer before passing it to a C function that expects a void pointer.

import "unsafe"

// Example: Passing a Go byte slice to a C function expecting a void pointer
func callCFunction(data []byte) {
    if len(data) == 0 {
        return
    }
    // Convert the address of the first byte to unsafe.Pointer
    C.someCFunction(unsafe.Pointer(&data[0]), C.size_t(len(data)))
}

Warning: The Go garbage collector is unaware of pointers held by C code. You must ensure the Go object (like data) remains referenced until the C function finishes using it to prevent the memory from being collected prematurely.