You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

474 lines
17 KiB

8 years ago
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <meta name="theme-color" content="#375EAB">
  7. <title>cgo - The Go Programming Language</title>
  8. <link type="text/css" rel="stylesheet" href="../../lib/godoc/style.css">
  9. <link rel="stylesheet" href="../../lib/godoc/jquery.treeview.css">
  10. <script type="text/javascript">window.initFuncs = [];</script>
  11. </head>
  12. <body>
  13. <div id='lowframe' style="position: fixed; bottom: 0; left: 0; height: 0; width: 100%; border-top: thin solid grey; background-color: white; overflow: auto;">
  14. ...
  15. </div><!-- #lowframe -->
  16. <div id="topbar" class="wide"><div class="container">
  17. <div class="top-heading" id="heading-wide"><a href="http://localhost:6060/">The Go Programming Language</a></div>
  18. <div class="top-heading" id="heading-narrow"><a href="http://localhost:6060/">Go</a></div>
  19. <a href="index.html#" id="menu-button"><span id="menu-button-arrow">&#9661;</span></a>
  20. <form method="GET" action="http://localhost:6060/search">
  21. <div id="menu">
  22. <a href="http://localhost:6060/doc/">Documents</a>
  23. <a href="http://localhost:6060/pkg/">Packages</a>
  24. <a href="http://localhost:6060/project/">The Project</a>
  25. <a href="http://localhost:6060/help/">Help</a>
  26. <a href="http://localhost:6060/blog/">Blog</a>
  27. <input type="text" id="search" name="q" class="inactive" value="Search" placeholder="Search">
  28. </div>
  29. </form>
  30. </div></div>
  31. <div id="page" class="wide">
  32. <div class="container">
  33. <h1>Command cgo</h1>
  34. <div id="nav"></div>
  35. <!--
  36. Copyright 2009 The Go Authors. All rights reserved.
  37. Use of this source code is governed by a BSD-style
  38. license that can be found in the LICENSE file.
  39. -->
  40. <!--
  41. Note: Static (i.e., not template-generated) href and id
  42. attributes start with "pkg-" to make it impossible for
  43. them to conflict with generated attributes (some of which
  44. correspond to Go identifiers).
  45. -->
  46. <script type='text/javascript'>
  47. document.ANALYSIS_DATA = null;
  48. document.CALLGRAPH = null;
  49. </script>
  50. <p>
  51. Cgo enables the creation of Go packages that call C code.
  52. </p>
  53. <h3 id="hdr-Using_cgo_with_the_go_command">Using cgo with the go command</h3>
  54. <p>
  55. To use cgo write normal Go code that imports a pseudo-package &#34;C&#34;.
  56. The Go code can then refer to types such as C.size_t, variables such
  57. as C.stdout, or functions such as C.putchar.
  58. </p>
  59. <p>
  60. If the import of &#34;C&#34; is immediately preceded by a comment, that
  61. comment, called the preamble, is used as a header when compiling
  62. the C parts of the package. For example:
  63. </p>
  64. <pre>// #include &lt;stdio.h&gt;
  65. // #include &lt;errno.h&gt;
  66. import &#34;C&#34;
  67. </pre>
  68. <p>
  69. The preamble may contain any C code, including function and variable
  70. declarations and definitions. These may then be referred to from Go
  71. code as though they were defined in the package &#34;C&#34;. All names
  72. declared in the preamble may be used, even if they start with a
  73. lower-case letter. Exception: static variables in the preamble may
  74. not be referenced from Go code; static functions are permitted.
  75. </p>
  76. <p>
  77. See $GOROOT/misc/cgo/stdio and $GOROOT/misc/cgo/gmp for examples. See
  78. &#34;C? Go? Cgo!&#34; for an introduction to using cgo:
  79. <a href="https://golang.org/doc/articles/c_go_cgo.html">https://golang.org/doc/articles/c_go_cgo.html</a>.
  80. </p>
  81. <p>
  82. CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS may be defined with pseudo #cgo
  83. directives within these comments to tweak the behavior of the C or C++
  84. compiler. Values defined in multiple directives are concatenated
  85. together. The directive can include a list of build constraints limiting its
  86. effect to systems satisfying one of the constraints
  87. (see <a href="https://golang.org/pkg/go/build/#hdr-Build_Constraints">https://golang.org/pkg/go/build/#hdr-Build_Constraints</a> for details about the constraint syntax).
  88. For example:
  89. </p>
  90. <pre>// #cgo CFLAGS: -DPNG_DEBUG=1
  91. // #cgo amd64 386 CFLAGS: -DX86=1
  92. // #cgo LDFLAGS: -lpng
  93. // #include &lt;png.h&gt;
  94. import &#34;C&#34;
  95. </pre>
  96. <p>
  97. Alternatively, CPPFLAGS and LDFLAGS may be obtained via the pkg-config
  98. tool using a &#39;#cgo pkg-config:&#39; directive followed by the package names.
  99. For example:
  100. </p>
  101. <pre>// #cgo pkg-config: png cairo
  102. // #include &lt;png.h&gt;
  103. import &#34;C&#34;
  104. </pre>
  105. <p>
  106. When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS and
  107. CGO_LDFLAGS environment variables are added to the flags derived from
  108. these directives. Package-specific flags should be set using the
  109. directives, not the environment variables, so that builds work in
  110. unmodified environments.
  111. </p>
  112. <p>
  113. All the cgo CPPFLAGS and CFLAGS directives in a package are concatenated and
  114. used to compile C files in that package. All the CPPFLAGS and CXXFLAGS
  115. directives in a package are concatenated and used to compile C++ files in that
  116. package. All the LDFLAGS directives in any package in the program are
  117. concatenated and used at link time. All the pkg-config directives are
  118. concatenated and sent to pkg-config simultaneously to add to each appropriate
  119. set of command-line flags.
  120. </p>
  121. <p>
  122. When the cgo directives are parsed, any occurrence of the string ${SRCDIR}
  123. will be replaced by the absolute path to the directory containing the source
  124. file. This allows pre-compiled static libraries to be included in the package
  125. directory and linked properly.
  126. For example if package foo is in the directory /go/src/foo:
  127. </p>
  128. <pre>// #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo
  129. </pre>
  130. <p>
  131. Will be expanded to:
  132. </p>
  133. <pre>// #cgo LDFLAGS: -L/go/src/foo/libs -lfoo
  134. </pre>
  135. <p>
  136. When the Go tool sees that one or more Go files use the special import
  137. &#34;C&#34;, it will look for other non-Go files in the directory and compile
  138. them as part of the Go package. Any .c, .s, or .S files will be
  139. compiled with the C compiler. Any .cc, .cpp, or .cxx files will be
  140. compiled with the C++ compiler. Any .h, .hh, .hpp, or .hxx files will
  141. not be compiled separately, but, if these header files are changed,
  142. the C and C++ files will be recompiled. The default C and C++
  143. compilers may be changed by the CC and CXX environment variables,
  144. respectively; those environment variables may include command line
  145. options.
  146. </p>
  147. <p>
  148. The cgo tool is enabled by default for native builds on systems where
  149. it is expected to work. It is disabled by default when
  150. cross-compiling. You can control this by setting the CGO_ENABLED
  151. environment variable when running the go tool: set it to 1 to enable
  152. the use of cgo, and to 0 to disable it. The go tool will set the
  153. build constraint &#34;cgo&#34; if cgo is enabled.
  154. </p>
  155. <p>
  156. When cross-compiling, you must specify a C cross-compiler for cgo to
  157. use. You can do this by setting the CC_FOR_TARGET environment
  158. variable when building the toolchain using make.bash, or by setting
  159. the CC environment variable any time you run the go tool. The
  160. CXX_FOR_TARGET and CXX environment variables work in a similar way for
  161. C++ code.
  162. </p>
  163. <h3 id="hdr-Go_references_to_C">Go references to C</h3>
  164. <p>
  165. Within the Go file, C&#39;s struct field names that are keywords in Go
  166. can be accessed by prefixing them with an underscore: if x points at a C
  167. struct with a field named &#34;type&#34;, x._type accesses the field.
  168. C struct fields that cannot be expressed in Go, such as bit fields
  169. or misaligned data, are omitted in the Go struct, replaced by
  170. appropriate padding to reach the next field or the end of the struct.
  171. </p>
  172. <p>
  173. The standard C numeric types are available under the names
  174. C.char, C.schar (signed char), C.uchar (unsigned char),
  175. C.short, C.ushort (unsigned short), C.int, C.uint (unsigned int),
  176. C.long, C.ulong (unsigned long), C.longlong (long long),
  177. C.ulonglong (unsigned long long), C.float, C.double,
  178. C.complexfloat (complex float), and C.complexdouble (complex double).
  179. The C type void* is represented by Go&#39;s unsafe.Pointer.
  180. The C types __int128_t and __uint128_t are represented by [16]byte.
  181. </p>
  182. <p>
  183. To access a struct, union, or enum type directly, prefix it with
  184. struct_, union_, or enum_, as in C.struct_stat.
  185. </p>
  186. <p>
  187. The size of any C type T is available as C.sizeof_T, as in
  188. C.sizeof_struct_stat.
  189. </p>
  190. <p>
  191. As Go doesn&#39;t have support for C&#39;s union type in the general case,
  192. C&#39;s union types are represented as a Go byte array with the same length.
  193. </p>
  194. <p>
  195. Go structs cannot embed fields with C types.
  196. </p>
  197. <p>
  198. Go code can not refer to zero-sized fields that occur at the end of
  199. non-empty C structs. To get the address of such a field (which is the
  200. only operation you can do with a zero-sized field) you must take the
  201. address of the struct and add the size of the struct.
  202. </p>
  203. <p>
  204. Cgo translates C types into equivalent unexported Go types.
  205. Because the translations are unexported, a Go package should not
  206. expose C types in its exported API: a C type used in one Go package
  207. is different from the same C type used in another.
  208. </p>
  209. <p>
  210. Any C function (even void functions) may be called in a multiple
  211. assignment context to retrieve both the return value (if any) and the
  212. C errno variable as an error (use _ to skip the result value if the
  213. function returns void). For example:
  214. </p>
  215. <pre>n, err := C.sqrt(-1)
  216. _, err := C.voidFunc()
  217. </pre>
  218. <p>
  219. Calling C function pointers is currently not supported, however you can
  220. declare Go variables which hold C function pointers and pass them
  221. back and forth between Go and C. C code may call function pointers
  222. received from Go. For example:
  223. </p>
  224. <pre>package main
  225. // typedef int (*intFunc) ();
  226. //
  227. // int
  228. // bridge_int_func(intFunc f)
  229. // {
  230. // return f();
  231. // }
  232. //
  233. // int fortytwo()
  234. // {
  235. // return 42;
  236. // }
  237. import &#34;C&#34;
  238. import &#34;fmt&#34;
  239. func main() {
  240. f := C.intFunc(C.fortytwo)
  241. fmt.Println(int(C.bridge_int_func(f)))
  242. // Output: 42
  243. }
  244. </pre>
  245. <p>
  246. In C, a function argument written as a fixed size array
  247. actually requires a pointer to the first element of the array.
  248. C compilers are aware of this calling convention and adjust
  249. the call accordingly, but Go cannot. In Go, you must pass
  250. the pointer to the first element explicitly: C.f(&amp;C.x[0]).
  251. </p>
  252. <p>
  253. A few special functions convert between Go and C types
  254. by making copies of the data. In pseudo-Go definitions:
  255. </p>
  256. <pre>// Go string to C string
  257. // The C string is allocated in the C heap using malloc.
  258. // It is the caller&#39;s responsibility to arrange for it to be
  259. // freed, such as by calling C.free (be sure to include stdlib.h
  260. // if C.free is needed).
  261. func C.CString(string) *C.char
  262. // C string to Go string
  263. func C.GoString(*C.char) string
  264. // C data with explicit length to Go string
  265. func C.GoStringN(*C.char, C.int) string
  266. // C data with explicit length to Go []byte
  267. func C.GoBytes(unsafe.Pointer, C.int) []byte
  268. </pre>
  269. <h3 id="hdr-C_references_to_Go">C references to Go</h3>
  270. <p>
  271. Go functions can be exported for use by C code in the following way:
  272. </p>
  273. <pre>//export MyFunction
  274. func MyFunction(arg1, arg2 int, arg3 string) int64 {...}
  275. //export MyFunction2
  276. func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
  277. </pre>
  278. <p>
  279. They will be available in the C code as:
  280. </p>
  281. <pre>extern int64 MyFunction(int arg1, int arg2, GoString arg3);
  282. extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);
  283. </pre>
  284. <p>
  285. found in the _cgo_export.h generated header, after any preambles
  286. copied from the cgo input files. Functions with multiple
  287. return values are mapped to functions returning a struct.
  288. Not all Go types can be mapped to C types in a useful way.
  289. </p>
  290. <p>
  291. Using //export in a file places a restriction on the preamble:
  292. since it is copied into two different C output files, it must not
  293. contain any definitions, only declarations. If a file contains both
  294. definitions and declarations, then the two output files will produce
  295. duplicate symbols and the linker will fail. To avoid this, definitions
  296. must be placed in preambles in other files, or in C source files.
  297. </p>
  298. <h3 id="hdr-Passing_pointers">Passing pointers</h3>
  299. <p>
  300. Go is a garbage collected language, and the garbage collector needs to
  301. know the location of every pointer to Go memory. Because of this,
  302. there are restrictions on passing pointers between Go and C.
  303. </p>
  304. <p>
  305. In this section the term Go pointer means a pointer to memory
  306. allocated by Go (such as by using the &amp; operator or calling the
  307. predefined new function) and the term C pointer means a pointer to
  308. memory allocated by C (such as by a call to C.malloc). Whether a
  309. pointer is a Go pointer or a C pointer is a dynamic property
  310. determined by how the memory was allocated; it has nothing to do with
  311. the type of the pointer.
  312. </p>
  313. <p>
  314. Go code may pass a Go pointer to C provided the Go memory to which it
  315. points does not contain any Go pointers. The C code must preserve
  316. this property: it must not store any Go pointers in Go memory, even
  317. temporarily. When passing a pointer to a field in a struct, the Go
  318. memory in question is the memory occupied by the field, not the entire
  319. struct. When passing a pointer to an element in an array or slice,
  320. the Go memory in question is the entire array or the entire backing
  321. array of the slice.
  322. </p>
  323. <p>
  324. C code may not keep a copy of a Go pointer after the call returns.
  325. </p>
  326. <p>
  327. A Go function called by C code may not return a Go pointer. A Go
  328. function called by C code may take C pointers as arguments, and it may
  329. store non-pointer or C pointer data through those pointers, but it may
  330. not store a Go pointer in memory pointed to by a C pointer. A Go
  331. function called by C code may take a Go pointer as an argument, but it
  332. must preserve the property that the Go memory to which it points does
  333. not contain any Go pointers.
  334. </p>
  335. <p>
  336. Go code may not store a Go pointer in C memory. C code may store Go
  337. pointers in C memory, subject to the rule above: it must stop storing
  338. the Go pointer when the C function returns.
  339. </p>
  340. <p>
  341. These rules are checked dynamically at runtime. The checking is
  342. controlled by the cgocheck setting of the GODEBUG environment
  343. variable. The default setting is GODEBUG=cgocheck=1, which implements
  344. reasonably cheap dynamic checks. These checks may be disabled
  345. entirely using GODEBUG=cgocheck=0. Complete checking of pointer
  346. handling, at some cost in run time, is available via GODEBUG=cgocheck=2.
  347. </p>
  348. <p>
  349. It is possible to defeat this enforcement by using the unsafe package,
  350. and of course there is nothing stopping the C code from doing anything
  351. it likes. However, programs that break these rules are likely to fail
  352. in unexpected and unpredictable ways.
  353. </p>
  354. <h3 id="hdr-Using_cgo_directly">Using cgo directly</h3>
  355. <p>
  356. Usage:
  357. </p>
  358. <pre>go tool cgo [cgo options] [-- compiler options] gofiles...
  359. </pre>
  360. <p>
  361. Cgo transforms the specified input Go source files into several output
  362. Go and C source files.
  363. </p>
  364. <p>
  365. The compiler options are passed through uninterpreted when
  366. invoking the C compiler to compile the C parts of the package.
  367. </p>
  368. <p>
  369. The following options are available when running cgo directly:
  370. </p>
  371. <pre>-dynimport file
  372. Write list of symbols imported by file. Write to
  373. -dynout argument or to standard output. Used by go
  374. build when building a cgo package.
  375. -dynout file
  376. Write -dynimport output to file.
  377. -dynpackage package
  378. Set Go package for -dynimport output.
  379. -dynlinker
  380. Write dynamic linker as part of -dynimport output.
  381. -godefs
  382. Write out input file in Go syntax replacing C package
  383. names with real values. Used to generate files in the
  384. syscall package when bootstrapping a new target.
  385. -objdir directory
  386. Put all generated files in directory.
  387. -importpath string
  388. The import path for the Go package. Optional; used for
  389. nicer comments in the generated files.
  390. -exportheader file
  391. If there are any exported functions, write the
  392. generated export declarations to file.
  393. C code can #include this to see the declarations.
  394. -gccgo
  395. Generate output for the gccgo compiler rather than the
  396. gc compiler.
  397. -gccgoprefix prefix
  398. The -fgo-prefix option to be used with gccgo.
  399. -gccgopkgpath path
  400. The -fgo-pkgpath option to be used with gccgo.
  401. -import_runtime_cgo
  402. If set (which it is by default) import runtime/cgo in
  403. generated output.
  404. -import_syscall
  405. If set (which it is by default) import syscall in
  406. generated output.
  407. -debug-define
  408. Debugging option. Print #defines.
  409. -debug-gcc
  410. Debugging option. Trace C compiler execution and output.
  411. </pre>
  412. <div id="footer">
  413. Build version go1.6.<br>
  414. Except as <a href="https://developers.google.com/site-policies#restrictions">noted</a>,
  415. the content of this page is licensed under the
  416. Creative Commons Attribution 3.0 License,
  417. and code is licensed under a <a href="http://localhost:6060/LICENSE">BSD license</a>.<br>
  418. <a href="http://localhost:6060/doc/tos.html">Terms of Service</a> |
  419. <a href="http://www.google.com/intl/en/policies/privacy/">Privacy Policy</a>
  420. </div>
  421. </div><!-- .container -->
  422. </div><!-- #page -->
  423. <!-- TODO(adonovan): load these from <head> using "defer" attribute? -->
  424. <script type="text/javascript" src="../../lib/godoc/jquery.js"></script>
  425. <script type="text/javascript" src="../../lib/godoc/jquery.treeview.js"></script>
  426. <script type="text/javascript" src="../../lib/godoc/jquery.treeview.edit.js"></script>
  427. <script type="text/javascript" src="../../lib/godoc/godocs.js"></script>
  428. </body>
  429. </html>