Version: v0.5.3 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2021 License: MIT Imports: 2 Imported by: 0



Package cgo is an implementation of

See for code review discussion.



This section is empty.


This section is empty.


This section is empty.


type Handle

type Handle uintptr

Handle provides a safe representation to pass Go values between C and Go back and forth. The zero value of a handle is not a valid handle, and thus safe to use as a sentinel in C APIs.

The underlying type of Handle may change, but the value is guaranteed to fit in an integer type that is large enough to hold the bit pattern of any pointer. For instance, on the Go side:

package main

extern void MyGoPrint(unsigned long long handle);
void myprint(unsigned long long handle);
import "C"
import "runtime/cgo"

//export MyGoPrint
func MyGoPrint(handle C.ulonglong) {
	h := cgo.Handle(handle)
	val := h.Value().(int)

func main() {
	val := 42
	// Output: 42

and on the C side:

// A Go function
extern void MyGoPrint(unsigned long long handle);

// A C function
void myprint(unsigned long long handle) {

func NewHandle

func NewHandle(v interface{}) Handle

NewHandle returns a handle for a given value. If a given value is a pointer, slice, map, channel, or function that refers to the same object, the returned handle will also be the same. Besides, nil value must not be used.

The handle is valid until the program calls Delete on it. The handle uses resources, and this package assumes that C code may hold on to the handle, so a program must explicitly call Delete when the handle is no longer needed.

The intended use is to pass the returned handle to C code, which passes it back to Go, which calls Value. See an example in the comments of the Handle definition.

func (Handle) Delete

func (h Handle) Delete()

Delete invalidates a handle. This method must be called when C code no longer has a copy of the handle, and the program no longer needs the Go value that associated with the handle.

The method panics if the handle is invalid already.

func (Handle) Value

func (h Handle) Value() interface{}

Value returns the associated Go value for a valid handle.

The method panics if the handle is invalid already.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL