From 5ac186975c8a792a4504060001df12fa3ba2ba4e Mon Sep 17 00:00:00 2001
From: Ian Lance Taylor
-Let’s look at what's happening here, starting with the import statement.
+Let's look at what's happening here, starting with the import statement.
@@ -45,7 +45,7 @@ package, using an ordinary Go type conversion:
{{code "/doc/progs/cgo1.go" `/func Random/` `/STOP/`}}
-Here’s an equivalent function that uses a temporary variable to illustrate
+Here's an equivalent function that uses a temporary variable to illustrate
the type conversion more explicitly:
-Cgo recognizes this comment and uses it as a header when compiling the C
-parts of the package. In this case it is just a simple include statement,
-but it can be any valid C code. The comment must be immediately before the
-line that imports
+There is a limitation: if your program uses any
+The
@@ -85,7 +105,7 @@ just like a documentation comment.
-Unlike Go, C doesn’t have an explicit string type. Strings in C are
+Unlike Go, C doesn't have an explicit string type. Strings in C are
represented by a zero-terminated array of chars.
Memory allocations made by C code are not known to Go's memory manager.
When you create a C string with srandom
functions.
{{code "/doc/progs/cgo1.go" `/package rand/` `/END/`}}
import
statement.
{{code "/doc/progs/cgo1.go" `/\/\*/` `/STOP/`}}
"C"
, without any intervening blank lines,
-just like a documentation comment.
+Cgo recognizes this comment. Any lines starting
+with #cgo
+followed
+by a space character are removed; these become directives for cgo.
+The remaining lines are used as a header when compiling the C parts of
+the package. In this case those lines are just a
+single #include
+statement, but they can be almost any C code. The #cgo
+directives are
+used to provide flags for the compiler and linker when building the C
+parts of the package.
+//export
+directives, then the C code in the comment may only include declarations
+(extern int f();
), not definitions (int f() {
+return 1; }
). You can use //export
directives to
+make Go functions accessible to C code.
+#cgo
and //export
directives are
+documented in
+the cgo documentation.
fputs
function from the
C.CString
(or any C memory
-allocation) you must remember to free the memory when you’re done with it
+allocation) you must remember to free the memory when you're done with it
by calling C.free
.
-For a simple, idiomatic example of a cgo-based package, see Russ Cox’s gosqlite. Also, the Go Project Dashboard lists several other @@ -155,6 +175,6 @@ cgo packages.
-Finally, if you’re curious as to how all this works internally, take a look -at the introductory comment of the runtime package’s cgocall.c. +Finally, if you're curious as to how all this works internally, take a look +at the introductory comment of the runtime package's cgocall.c.