见代码:
foo.h
void foo(); void callgo(); void hello(); void print_x(char *str);
foo.c
/* gcc -c foo.c ar rv libfoo.a foo.o */ #include "foo.h" #include "stdio.h" #include "_obj/_cgo_export.h" //此文件为cgo自动生成,内容包含go语言的类型及相关函数声明。 void foo() { printf("I am foo!\n"); } void callgo() { MyGoFunction(1,2); //此为go函数, 在_cgo_export.h中声明。 } void hello() { printf("Hello, Cgo! -- from C world.\n"); } void print_x(char *str) { printf("%s\n", str); }
test.go
package main import ( "fmt" ) /* #include <stdlib.h> #include <stdio.h> #include "foo.h" */ import "C" import "unsafe" func Random() int { return int(C.random()) } func Seed(i int) { C.srandom(C.uint(i)) }
//注意,此处必须用export “函数名“” 导出,这样才能被c调用。 //export MyGoFunction func MyGoFunction(arg1, arg2 int) int64 { fmt.Printf("arg1: %d, arg2: %d\n", arg1, arg2) return int64(arg1 + arg2) } func main() { Seed(100) fmt.Println("Random: ", Random()) C.hello() //pass parameters from go to c function. s := "Hello Cgo" cs := C.CString(s) defer C.free(unsafe.Pointer(cs)) C.print_x(cs) //call c function in lib. C.foo() //call go from c. C.callgo() }
构建步骤:
1.
//在$(GOPATH)/src中执行以下命令,生成 _cgo_export.h
//go tool cgo test.go
注意: 以上命令将在$(GOPATH)/src中生成_obj目录, 里面主要包含_cgo_export.h
//在$(GOPATH)/src中,执行以下命令,生成可执行文件test
go build
若以上两部都无错, 则成功。
注意: _obj 是cgo为 go build生成的, go build将自动去那里找相关c声明。
参考: https://medium.com/using-go-in-mobile-apps/using-go-in-mobile-apps-part-1-calling-go-functions-from-c-be1ecf7dfbc6#.9kr0e8j0c
http://tonybai.com/2012/09/26/interoperability-between-go-and-c/
代码放在: https://github.com/yujinliang/c_go_call
注意: 此文章只是我个人笔记, 如有错漏,请一定指正, 共同学习, 我的邮箱: htyu_0203_39@sina.com