介绍
这篇文章主要介绍了去语言中CGO怎么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。
1。去语言调用C函数例子:
package 主要 ,////,引用的C头文件需要在注释中声明,紧接着注释需要有import “C",且这一行和注释之间不能有空格//,/* # include & lt; stdio.h> # include & lt; stdlib.h> # include & lt; unistd.h> void myprint (char *, s), { printf (“% s \ n",, s); } */import “C" , , import ( “fmt" “unsafe" ) , func main (), {//使用C.CString创建的字符串需要手动释放。 cs :=, C.CString (“Hello 世界\ n") C.myprint (cs) C.free (unsafe.Pointer (cs)) fmt.Println (“call  C.sleep for 3 s") C.sleep (3) 返回 }
运行:
2。去语言调用C库函数:
你好。c
# include & lt; stdio.h> void hello () { ,,,printf (“hello 世界\ n"),, }
你好。h
# ifndef HELLO_H # define HELLO_H , void 你好(无效); # endif
编译:
gcc -c 安全 ar -cru  libhello.a ,你好。o
package 主要 ,//使用# cgo定义库路径 , ,/* # cgo CFLAGS:小姐,。 # cgo LDFLAGS: -L 只-lhello # include “hello.h" */import “C" , func main (), { C.hello () }
运行:
3。去语言导出函数给C语言使用:
主要。去
package 主要 ,////# include & lt; stdio.h>//int 添加(int ,, int b);//import “C" , import ( “fmt" ) ,//当使用出口的时候,在同一个文件中就不能再定义其它的c函数了,不然会报的错。//使用出口导出函数给c语言调用。 ,//export GoAdd func GoAdd (a, b int), int { return a  + b } , func main (), { a :=, C.add (1, 2) fmt.Printf (“C.add (1、2), return % d \ n",,) }
cfunc。去
package 主要 ,////int GoAdd (int ,, int b),,////int 添加(int ,, int b)//{//,,return GoAdd (a, b);//}//import “C"
运行:
4。去语言导出函数指针给c语言使用:
还有一种使用方式,这种是我使用比较多的。就是传递函数指针,因为去函数无法取址,因此需要写个中间函数做个转换操作,例子如下:
clibrary。c
# include & lt; stdio.h> , # include “clibrary.h" ,//参数是函数指针 void some_c_func (callback_fcn 回调) { int arg =, 2; printf (“C.some_c_func ():, calling callback with arg =, % d \ n",, arg); int response =,回调(2); printf (“C.some_c_func ():, callback responded with % d \ n",,响应); }
, clibrary。h
# ifndef CLIBRARY_H # define CLIBRARY_H//定义函数指针 typedef int (* callback_fcn) (int); void some_c_func (callback_fcn); # endif
代码:
package 主要 ,/* # cgo CFLAGS:小姐,。 # cgo LDFLAGS: -L 只-lclibrary # include “clibrary.h" int callOnMeGo_cgo (int );,//,声明 */import “C" , import ( “fmt" “unsafe" ) ,//export callOnMeGo func callOnMeGo (int)拷贝,int { return 拷贝+ 1 } , func main (), { fmt.Printf (“Go.main (): calling C function with callback 用我们\ n") , ,,,//使用unsafe.Pointer转换 C.some_c_func ((C.callback_fcn) (unsafe.Pointer (C.callOnMeGo_cgo))) }去语言中CGO怎么用