在Go語言中調(diào)用C接口需要使用cgo
工具。下面是一個(gè)簡(jiǎn)單的示例,演示了如何在Go語言中調(diào)用一個(gè)用C語言編寫的庫中的函數(shù)。
首先,創(chuàng)建一個(gè)C語言的源文件example.c
,包含一個(gè)簡(jiǎn)單的函數(shù)hello()
:
#include <stdio.h>
void hello() {
printf("Hello from C!\n");
}
接下來,創(chuàng)建一個(gè)Go語言的源文件main.go
,在文件中使用cgo
工具引入C語言的頭文件,并調(diào)用C語言的函數(shù)hello()
:
package main
// #include "example.c"
import "C"
func main() {
C.hello()
}
然后,在命令行中執(zhí)行以下命令編譯并運(yùn)行這個(gè)程序:
go run main.go
你將會(huì)看到輸出Hello from C!
,這表明Go語言成功地調(diào)用了C語言的函數(shù)。