go代碼
package main
import(
"C"
)
func main(){}
// 上面都是固定的,需要其他包的話自行導入
// 定義函數,可定義多個,每個函數都要export
//export HelloWorld
func HelloWorld(info *C.char) *C.char {
GoStr := C.GoString(info)
GoStr += "123"
return C.CString(GoStr)
}
編譯
go build -buildmode=c-shared -o hello.so hello.go
編譯後生成hello.so和hello.h,python中隻需要so檔案。
pythob中調用
# python3
import os
from ctypes import cdll, c_char_p
# 導包
lib = cdll.LoadLibrary(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'hello.so'))
# 擷取函數
hello = lib.HelloWorld
hello.argtype = c_char_p
hello.restype = c_char_p
# 調用
print(hello(b"guido"))