英文:
Interface Go with C libraries
问题
如何将Go程序与C库进行接口?
我一直在浏览Go的源代码,但我还没有弄清楚。如果有人已经做过,请分享一下,谢谢!
**更新:**感谢@fserb,我在这里发布一些来自Go源代码的文档:
Cgo使得可以创建调用C代码的Go包。
用法:cgo [编译器选项] file.go
编译器选项在调用gcc编译包的C部分时会被原样传递。
输入的file.go是一个语法上有效的Go源文件,它导入了伪包"C",然后引用了诸如C.size_t这样的类型,诸如C.stdout这样的变量,或者诸如C.putchar这样的函数。
如果"C"的导入紧接着一个注释,那个注释将被用作编译包的C部分的头文件。例如:
// #include <stdio.h>
// #include <errno.h>
import "C"Cgo将输入文件转换为四个输出文件:两个Go源文件,一个用于6c(或8c或5c)的C文件,以及一个用于gcc的C文件。
在Make.pkg中的标准包makefile规则自动化了使用cgo的过程。请参阅$GOROOT/misc/cgo/stdio和$GOROOT/misc/cgo/gmp以获取示例。
Cgo目前不支持gccgo。
英文:
How does one interface a Go program with a C library?
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?
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.
答案1
得分: 20
请查看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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论