{{tag>Brouillon Dev Code Go Python}} # Inclure des appels à Go lang dans Python Voir : * https://fluhus.github.io/snopher/ et https://github.com/fluhus/snopher Voir aussi : * [[Executer du code Python avec Go lang]] ## Tuto 1 Source : https://dev.to/leapcell/how-to-call-go-code-in-python-accelerate-python-with-go-54if Linux and Mac ~~~bash go build -buildmode=c-shared -o add.so add.go ~~~ windows ~~~bash go build -buildmode=c-shared -o add.dll add.go ~~~ ~~~bash go build -ldflags "-s -w" -buildmode=c-shared -o add.so add.go ~~~ `-s` indicates compression `-w` indicates removing debugging ~~~python # Test calling code written in the GO language from Python # First, the GO code needs to be compiled into a dynamic link library from ctypes import cdll lib = cdll.LoadLibrary("./add.so") # Specify the compiled dynamic link library file here # Call the Add function in the GO language result = lib.Add(100, 200) print("result ", result) # Call the PrintDll function in the GO language lib.PrintDll() ~~~ ## Tuto 2 Source : https://medium.com/analytics-vidhya/running-go-code-from-python-a65b3ae34a2d ### Exemple 1 `library.go` ~~~go package main import ( "C" "log" ) //export helloWorld func helloWorld(){ log.Println("Hello World") } func main(){ } ~~~ Compilation de la lib ~~~bash go build -buildmode=c-shared -o library.so library.go ~~~ Execution depuis Python ~~~python import ctypes library = ctypes.cdll.LoadLibrary('./library.so') hello_world = library.helloWorld hello_world() ~~~ ### Exemple 2 `library.go` ~~~go //export hello func hello(namePtr *C.char){ name := C.GoString(namePtr) log.Println("Hello", name) } ~~~ `app.py` ~~~python hello = library.hello hello.argtypes = [ctypes.c_char_p] hello("everyone".encode('utf-8')) ~~~ `library.go` ~~~go //export farewell func farewell() *C.char{ return C.CString("Bye!") } ~~~ FIXME