与 C 库的接口 Go [英] Interface Go with C libraries
问题描述
如何将 Go 程序与 C 库连接起来?
How does one interface a Go program with a C library?
我一直在浏览 Go 的源代码,但我仍然没有弄清楚.如果有人已经这样做了,可以分享一下吗?
I've been browsing Go's source code but I still didn't figured it out. If someone has already done so, could you share, please?
更新:感谢@fserb,我发布了一些来自 Go 来源的文档:
UPDATED: Thanks to @fserb, I am posting some documentation from the Go sources:
Cgo 使创建 Go 成为可能调用 C 代码的包.
Cgo enables the creation of Go packages that call C code.
用法:cgo [编译器选项] file.go
Usage: cgo [compiler options] file.go
编译器选项被传递通过在调用时未解释gcc 来编译 C 部分包.
The compiler options are passed through uninterpreted when invoking gcc to compile the C parts of the package.
输入 file.go 在语法上是一个导入的有效 Go 源文件伪包C"然后指类型如 C.size_t,变量如作为 C.stdout,或函数如C.putchar.
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.
如果立即导入C"在评论之前,该评论是在编译 C 时用作头文件包裹的一部分.例如:
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 将输入文件转换为四个输出文件:两个 Go 源码文件,用于 6c(或 8c 或 5c)的 C 文件,和 gcc 的 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.
标准包makefile规则在Make.pkg 自动化使用过程cgo.见 $GOROOT/misc/cgo/stdio 和$GOROOT/misc/cgo/gmp 示例.
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 还不能与 gccgo 一起使用.
Cgo does not yet work with gccgo.
推荐答案
检查 cgo.另外,请查看 Go 源代码中的 misc/cgo/gmp 以获取有关如何在 Go 中包装 C 库的示例代码.
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.
这篇关于与 C 库的接口 Go的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!