cgo

package
Version: v0.5.3 Latest Latest
Warning

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

Documentation

Overview

Package cgo is an implementation of golang.org/issue/37033.

See golang.org/cl/294670 for code review discussion.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

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)
	println(val)
	h.Delete()
}

func main() {
	val := 42
	C.myprint(C.ulonglong(cgo.NewHandle(val)))
	// 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) {
    MyGoPrint(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