This is a creation in Article, where the information may have evolved or changed.
2014-06-10 WCDJ
absrtact : This article mainly introduces how to implement Call C interface in Golang. Because Go's official website is often the wall, causes unable to browse the official detailed document, occasionally in browses Golang the source code to find some about the CGO usage, the concrete path in the Go/misc/cgo directory.
For example, in the Go/misc/cgo/gmp/gmp.go file, you can find ways to refer to the C library in Golang:
An example of wrapping a C library in Go. This is the GNU multiprecision Library GMP's integer type mpz_t wrapped to look like the Go package big ' s integer type Int .
The following is a simple example: hello.go
The complete code can be viewed here: https://github.com/gerryyang/goinaction/blob/master/src/cgo/src/hello.go
Package main/* #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include ". /inc/hello.h "//intentionally write the same ldflags DIFFERENTLY#CGO Linux ldflags:-L. /lib-lhello#cgo Darwin Ldflags:-L. /lib-lhello#if 0void Hello (const char *name) {printf ("%s\n", name); return;} #endif */import "C" Import ("FMT" "Time") func Hello (s string) {cs: = c.cstring (s) C.hello (CS)}func Main () {Seed (+) fmt. PRINTLN (int (c.random ())) time. Sleep (time. Duration (1) * time. Second) fmt. PRINTLN (int (c.random ())) Fmt. Println ("Getpid:", int (C.getpid ())) C.puts (C.cstring ("Call C-puts")) Hello ("Call C ' s go wrapper func") C.hello (c.cstring ("Call C Hello func")} Func Seed (i int) {c.srandom (C.uint (i))}
Reference
[1] http://www.cnblogs.com/yjf512/archive/2012/07/19/2599304.html
[2] http://tonybai.com/tag/cgo/