与C库一起使用的接口

huangapple go评论99阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2009年11月19日 10:08:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/1760468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定