您的位置:首页 > 编程语言 > Go语言

cgo

2017-08-02 12:49 756 查看
...



package main

import "fmt"

func main() {
fmt.Println("Hello, 世界")
}

RunFormatShare

Command cgo

Cgo enables the creation of Go packages that call C code.

Using cgo with the go command

To use cgo write normal Go code that imports a pseudo-package "C".The Go code can then refer to types such as C.size_t, variables suchas C.stdout, or functions such as C.putchar.

If the import of "C" is immediately preceded by a comment, thatcomment, called the preamble, is used as a header when compilingthe C parts of the package. For example:

// #include <stdio.h>
// #include <errno.h>
import "C"

The preamble may contain any C code, including function and variabledeclarations and definitions. These may then be referred to from Gocode as though they were defined in the package "C". All namesdeclared in the preamble may be used, even if they start
with alower-case letter. Exception: static variables in the preamble maynot be referenced from Go code; static functions are permitted.

See $GOROOT/misc/cgo/stdio and $GOROOT/misc/cgo/gmp for examples. See"C? Go? Cgo!" for an introduction to using cgo:https://golang.org/doc/articles/c_go_cgo.html.

CFLAGS, CPPFLAGS, CXXFLAGS, FFLAGS and LDFLAGS may be defined with pseudo#cgo directives within these comments to tweak the behavior of the C, C++or Fortran compiler. Values defined in multiple directives are concatenatedtogether. The directive can include
a list of build constraints limiting itseffect to systems satisfying one of the constraints(see
https://golang.org/pkg/go/build/#hdr-Build_Constraints for details about the constraint syntax).For example:

// #cgo CFLAGS: -DPNG_DEBUG=1
// #cgo amd64 386 CFLAGS: -DX86=1
// #cgo LDFLAGS: -lpng
// #include <png.h>
import "C"

Alternatively, CPPFLAGS and LDFLAGS may be obtained via the pkg-configtool using a '#cgo pkg-config:' directive followed by the package names.For example:

// #cgo pkg-config: png cairo
// #include <png.h>
import "C"

The default pkg-config tool may be changed by setting the PKG_CONFIG environment variable.

When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS, CGO_FFLAGS andCGO_LDFLAGS environment variables are added to the flags derived fromthese directives. Package-specific flags should be set using thedirectives, not the environment variables, so that
builds work inunmodified environments.

All the cgo CPPFLAGS and CFLAGS directives in a package are concatenated andused to compile C files in that package. All the CPPFLAGS and CXXFLAGSdirectives in a package are concatenated and used to compile C++ files in thatpackage. All the CPPFLAGS and
FFLAGS directives in a package are concatenatedand used to compile Fortran files in that package. All the LDFLAGS directivesin any package in the program are concatenated and used at link time. All thepkg-config directives are concatenated and sent to pkg-config
simultaneouslyto add to each appropriate set of command-line flags.

When the cgo directives are parsed, any occurrence of the string ${SRCDIR}will be replaced by the absolute path to the directory containing the sourcefile. This allows pre-compiled static libraries to be included in the packagedirectory and linked properly.For
example if package foo is in the directory /go/src/foo:

// #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo

Will be expanded to:

// #cgo LDFLAGS: -L/go/src/foo/libs -lfoo

When the Go tool sees that one or more Go files use the special import"C", it will look for other non-Go files in the directory and compilethem as part of the Go package. Any .c, .s, or .S files will becompiled with the C compiler. Any .cc, .cpp, or .cxx
files will becompiled with the C++ compiler. Any .f, .F, .for or .f90 files will becompiled with the fortran compiler. Any .h, .hh, .hpp, or .hxx files willnot be compiled separately, but, if these header files are changed,the C and C++ files will be recompiled.
The default C and C++compilers may be changed by the CC and CXX environment variables,respectively; those environment variables may include command lineoptions.

The cgo tool is enabled by default for native builds on systems whereit is expected to work. It is disabled by default whencross-compiling. You can control this by setting the CGO_ENABLEDenvironment variable when running the go tool: set it to 1 to enablethe
use of cgo, and to 0 to disable it. The go tool will set thebuild constraint "cgo" if cgo is enabled.

When cross-compiling, you must specify a C cross-compiler for cgo touse. You can do this by setting the CC_FOR_TARGET environmentvariable when building the toolchain using make.bash, or by settingthe CC environment variable any time you run the go tool.
TheCXX_FOR_TARGET and CXX environment variables work in a similar way forC++ code.

Go references to C

Within the Go file, C's struct field names that are keywords in Gocan be accessed by prefixing them with an underscore: if x points at a Cstruct with a field named "type", x._type accesses the field.C struct fields that cannot be expressed in Go, such as
bit fieldsor misaligned data, are omitted in the Go struct, replaced byappropriate padding to reach the next field or the end of the struct.

The standard C numeric types are available under the namesC.char, C.schar (signed char), C.uchar (unsigned char),C.short, C.ushort (unsigned short), C.int, C.uint (unsigned int),C.long, C.ulong (unsigned long), C.longlong (long long),C.ulonglong (unsigned
long long), C.float, C.double,C.complexfloat (complex float), and C.complexdouble (complex double).The C type void* is represented by Go's unsafe.Pointer.The C types __int128_t and __uint128_t are represented by [16]byte.

To access a struct, union, or enum type directly, prefix it withstruct_, union_, or enum_, as in C.struct_stat.

The size of any C type T is available as C.sizeof_T, as inC.sizeof_struct_stat.

As Go doesn't have support for C's union type in the general case,C's union types are represented as a Go byte array with the same length.

Go structs cannot embed fields with C types.

Go code cannot refer to zero-sized fields that occur at the end ofnon-empty C structs. To get the address of such a field (which is theonly operation you can do with a zero-sized field) you must take theaddress of the struct and add the size of the struct.

Cgo translates C types into equivalent unexported Go types.Because the translations are unexported, a Go package should notexpose C types in its exported API: a C type used in one Go packageis different from the same C type used in another.

Any C function (even void functions) may be called in a multipleassignment context to retrieve both the return value (if any) and theC errno variable as an error (use _ to skip the result value if thefunction returns void). For example:

n, err = C.sqrt(-1)
_, err := C.voidFunc()
var n, err = C.sqrt(1)

Calling C function pointers is currently not supported, however you candeclare Go variables which hold C function pointers and pass themback and forth between Go and C. C code may call function pointersreceived from Go. For example:

package main

// typedef int (*intFunc) ();
//
// int
// bridge_int_func(intFunc f)
// {
//		return f();
// }
//
// int fortytwo()
// {
//	    return 42;
// }
import "C"
import "fmt"

func main() {
f := C.intFunc(C.fortytwo)
fmt.Println(int(C.bridge_int_func(f)))
// Output: 42
}

In C, a function argument written as a fixed size arrayactually requires a pointer to the first element of the array.C compilers are aware of this calling convention and adjustthe call accordingly, but Go cannot. In Go, you must passthe pointer to the first
element explicitly: C.f(&C.x[0]).

A few special functions convert between Go and C typesby making copies of the data. In pseudo-Go definitions:

// Go string to C string
// The C string is allocated in the C heap using malloc.
// It is the caller's responsibility to arrange for it to be
// freed, such as by calling C.free (be sure to include stdlib.h
// if C.free is needed).
func C.CString(string) *C.char

// Go []byte slice to C array
// The C array is allocated in the C heap using malloc.
// It is the caller's responsibility to arrange for it to be
// freed, such as by calling C.free (be sure to include stdlib.h
// if C.free is needed).
func C.CBytes([]byte) unsafe.Pointer

// C string to Go string
func C.GoString(*C.char) string

// C data with explicit length to Go string
func C.GoStringN(*C.char, C.int) string

// C data with explicit length to Go []byte
func C.GoBytes(unsafe.Pointer, C.int) []byte

As a special case, C.malloc does not call the C library malloc directlybut instead calls a Go helper function that wraps the C library mallocbut guarantees never to return nil. If C's malloc indicates out of memory,the helper function crashes the program,
like when Go itself runs outof memory. Because C.malloc cannot fail, it has no two-result formthat returns errno.

C references to Go

Go functions can be exported for use by C code in the following way:

//export MyFunction
func MyFunction(arg1, arg2 int, arg3 string) int64 {...}

//export MyFunction2
func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}

They will be available in the C code as:

extern int64 MyFunction(int arg1, int arg2, GoString arg3);
extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);

found in the _cgo_export.h generated header, after any preamblescopied from the cgo input files. Functions with multiplereturn values are mapped to functions returning a struct.Not all Go types can be mapped to C types in a useful way.

Using //export in a file places a restriction on the preamble:since it is copied into two different C output files, it must notcontain any definitions, only declarations. If a file contains bothdefinitions and declarations, then the two output files will
produceduplicate symbols and the linker will fail. To avoid this, definitionsmust be placed in preambles in other files, or in C source files.

Passing pointers

Go is a garbage collected language, and the garbage collector needs toknow the location of every pointer to Go memory. Because of this,there are restrictions on passing pointers between Go and C.

In this section the term Go pointer means a pointer to memoryallocated by Go (such as by using the & operator or calling thepredefined new function) and the term C pointer means a pointer tomemory allocated by C (such as by a call to C.malloc). Whether apointer
is a Go pointer or a C pointer is a dynamic propertydetermined by how the memory was allocated; it has nothing to do withthe type of the pointer.

Go code may pass a Go pointer to C provided the Go memory to which itpoints does not contain any Go pointers. The C code must preservethis property: it must not store any Go pointers in Go memory, eventemporarily. When passing a pointer to a field in a struct,
the Gomemory in question is the memory occupied by the field, not the entirestruct. When passing a pointer to an element in an array or slice,the Go memory in question is the entire array or the entire backingarray of the slice.

C code may not keep a copy of a Go pointer after the call returns.

A Go function called by C code may not return a Go pointer. A Gofunction called by C code may take C pointers as arguments, and it maystore non-pointer or C pointer data through those pointers, but it maynot store a Go pointer in memory pointed to by a C
pointer. A Gofunction called by C code may take a Go pointer as an argument, but itmust preserve the property that the Go memory to which it points doesnot contain any Go pointers.

Go code may not store a Go pointer in C memory. C code may store Gopointers in C memory, subject to the rule above: it must stop storingthe Go pointer when the C function returns.

These rules are checked dynamically at runtime. The checking iscontrolled by the cgocheck setting of the GODEBUG environmentvariable. The default setting is GODEBUG=cgocheck=1, which implementsreasonably cheap dynamic checks. These checks may be disabledentirely
using GODEBUG=cgocheck=0. Complete checking of pointerhandling, at some cost in run time, is available via GODEBUG=cgocheck=2.

It is possible to defeat this enforcement by using the unsafe package,and of course there is nothing stopping the C code from doing anythingit likes. However, programs that break these rules are likely to failin unexpected and unpredictable ways.

Using cgo directly

Usage:

go tool cgo [cgo options] [-- compiler options] gofiles...

Cgo transforms the specified input Go source files into several outputGo and C source files.

The compiler options are passed through uninterpreted wheninvoking the C compiler to compile the C parts of the package.

The following options are available when running cgo directly:

-dynimport file
Write list of symbols imported by file. Write to
-dynout argument or to standard output. Used by go
build when building a cgo package.
-dynout file
Write -dynimport output to file.
-dynpackage package
Set Go package for -dynimport output.
-dynlinker
Write dynamic linker as part of -dynimport output.
-godefs
Write out input file in Go syntax replacing C package
names with real values. Used to generate files in the
syscall package when bootstrapping a new target.
-srcdir directory
Find the Go input files, listed on the command line,
in directory.
-objdir directory
Put all generated files in directory.
-importpath string
The import path for the Go package. Optional; used for
nicer comments in the generated files.
-exportheader file
If there are any exported functions, write the
generated export declarations to file.
C code can #include this to see the declarations.
-gccgo
Generate output for the gccgo compiler rather than the
gc compiler.
-gccgoprefix prefix
The -fgo-prefix option to be used with gccgo.
-gccgopkgpath path
The -fgo-pkgpath option to be used with gccgo.
-import_runtime_cgo
If set (which it is by default) import runtime/cgo in
generated output.
-import_syscall
If set (which it is by default) import syscall in
generated output.
-debug-define
Debugging option. Print #defines.
-debug-gcc
Debugging option. Trace C compiler execution and output.

Build version go1.8.3.

Except as
noted,the content of this page is licensed under theCreative Commons Attribution 3.0 License,and code is licensed under a
BSD license.
Terms of Service |
Privacy Policy
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: