开发者

Interface Go with C libraries

How does one interface a Go program with a C library?

I've been browsing开发者_C百科 Go's source code but I still didn't figured it out. If someone has already done so, could you share, please?

UPDATED: Thanks to @fserb, I am posting some documentation from the Go sources:

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

Usage: cgo [compiler options] file.go

The compiler options are passed through uninterpreted when invoking gcc to compile the C parts of the package.

The input file.go is a syntactically valid Go source file that imports the pseudo-package "C" and then refers to types such as C.size_t, variables such as C.stdout, or functions such as C.putchar.

If the import of "C" is immediately preceded by a comment, that comment is used as a header when compiling the C parts of the package. For example:

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

Cgo transforms the input file into four output files: two Go source files, a C file for 6c (or 8c or 5c), and a C file for gcc.

The standard package makefile rules in Make.pkg automate the process of using cgo. See $GOROOT/misc/cgo/stdio and $GOROOT/misc/cgo/gmp for examples.

Cgo does not yet work with gccgo.


Check cgo. Also, take a look at misc/cgo/gmp on the Go source code for an example code on how to wrap a C library in Go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜