這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
版本:go version go1.8.3 linux/amd64
go語言產生c語言的so庫在網上已經很多資料了,由於項目需要python和go結合,而python又可以調用c語言的so庫,所以嘗試了一下
在GOPATH目錄的src下建立一個test的檔案夾,裡面建立一個test.go
test.go代碼
package mainimport "C"//export Hellofunc Hello() string { return "Hello"}//export Testfunc Test(){ println("test");}func main() {}
使用命令產生libhello.so和libhello.h
go build -x -v -ldflags "-s -w" -buildmode=c-shared -o libhello.so test
由於Hello函數返回的是一個GoString,而GoString在libhello.h下的聲明是
typedef struct { const char *p; GoInt n; } GoString;
可見是一個結構體,所以使用python調用的時候需要使用ctypes庫轉換一下
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()
輸出結果
5Hellotest