Outils pour utilisateurs

Outils du site


tech:inclure_des_appels_a_go_lang_dans_python

Inclure des appels à Go lang dans Python

Tuto 1

Source : https://dev.to/leapcell/how-to-call-go-code-in-python-accelerate-python-with-go-54if

Linux and Mac

go build -buildmode=c-shared -o add.so add.go

windows

go build -buildmode=c-shared -o add.dll add.go
go build -ldflags "-s -w" -buildmode=c-shared -o add.so add.go

-s indicates compression -w indicates removing debugging

# 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

Exemple 1

library.go

package main
 
import (
   "C"
   "log"
)
 
//export helloWorld
func helloWorld(){
   log.Println("Hello World")
}
 
func main(){
 
}

Compilation de la lib

go build -buildmode=c-shared -o library.so library.go

Execution depuis Python

import ctypes
library = ctypes.cdll.LoadLibrary('./library.so')
hello_world = library.helloWorld
hello_world()

Exemple 2

library.go

//export hello
func hello(namePtr *C.char){
   name := C.GoString(namePtr)
   log.Println("Hello", name)
}

app.py

hello = library.hello
hello.argtypes = [ctypes.c_char_p]
hello("everyone".encode('utf-8'))

library.go

//export farewell
func farewell() *C.char{
   return C.CString("Bye!")
}

FIXME

tech/inclure_des_appels_a_go_lang_dans_python.txt · Dernière modification : de Jean-Baptiste

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki