Recently due to work reasons, it is necessary to implement mutual calls between go language and c language. Since the Go language and the C language are inextricably linked, the calls between the two can be realized at the language level. Below is a summary of this.
go language calls c language
The following is a brief example:
package main // #include <stdio.h> // #include <stdlib.h> /* void print(char *str) { printf("%s\n", str); } */ import "C" import "unsafe" func main() { s := "Hello Cgo" cs := C.CString(s) C.print(cs) C.free(unsafe.pointer(cs)) }
Compared with "normal" go code, the above code has several "special" features Place:
The include word of the c language header file appears in the opening comment
The c language function print# is defined in the comment
- ##Imported a "package" named C
- The c language function print defined above was called in the main function
#cgo indicator to specify which shared libraries the go source code will be linked with after compilation. The example is as follows:
// hello.go package main // #cgo LDFLAGS: -L ./ -lhello // #include <stdio.h> // #include <stdlib.h> // #include "hello.h" import "C" func main() { C.hello() } // hello.c #include "hello.h" void hello() { printf("hello, go\n"); } // hello.h extern void hello();
LDFLAGS: -L ./ -lhello after the
#cgo indicator, which is used to compile the go code When , specify to search the so library in the current directory and link it.
gcc -fPIC -o libhello.so hello.c
go build -o hello
./hello
// hello.go package main import "C" import "fmt" // export Go2C func Go2C() { fmt.Println("hello, C") }
go build. Note that main and main functions must exist when compiling the so library (even if the main function is empty). The compilation instructions are as follows:
go build -v -x -buildmode=c-shared -o libhello.so hello.go.
// hello.c #include <stdio.h> #include "libhello.h" int main() { Go2C(); return 0; }
gcc -o hello -L. -lhello. Note that before running, you must make sure that the shared library that needs to be linked exists in the shared library runtime search path. You can put the so library path in /usr/lib or modify the environment variable LD_LIBRARY_PATH.
go buildCompile go code into a shared library for use by c code. Note that the shared libraries in this article are all dynamic shared libraries. As for static shared libraries, they have not been tested. Those who are interested can implement them.