This is a creation in Article, where the information may have evolved or changed.
Version: Go version go1.8.3 linux/amd64
The go language generated C language so library on the internet has a lot of information, because the project needs Python and go to combine, and Python can call the C language so library, so try a bit
Create a new test folder in the Gopath directory under SRC, and create a new test.go
Test.go Code
package mainimport "C"//export Hellofunc Hello() string { return "Hello"}//export Testfunc Test(){ println("test");}func main() {}
Using commands to generate libhello.so and libhello.h
go build -x -v -ldflags "-s -w" -buildmode=c-shared -o libhello.so test
Since the Hello function returns a gostring, the gostring declaration under Libhello.h is
typedef struct { const char *p; GoInt n; } GoString;
Visible is a struct, so when using Python calls you need to use the cTYPES library to convert
from ctypes import * class StructPointer(Structure): _fields_ = [("p", c_char_p), ("n", c_longlong)] if __name__ == "__main__": lib = cdll.LoadLibrary("./libhello.so") lib.Hello.restype = StructPointer str = lib.Hello() print(str.n) #str.n是GoString返回字符的长度,没有截取的话后面会跟着一大串字符串 print(str.p[:str.n]) lib.Test()
Output results
5Hellotest