如何把 golang 与 python 集成?组装 golang 和 python。配备 gopath 环境变量。组装cgo golang 包。建立 golang 项目。为 python部件撰写 golang wrapper函数。在 python工程中建立模块。应用 cgo 搭建 golang 项目。在 golang 代码中启用 python函数。运作 golang 程序。
Golang 架构与 Python 集成
有时,您可能需要在 Golang 应用程序中应用 Python 部件。本指南将向您展现如何把 Golang 与 Python 集成,并提供一个实战案例 。
前提条件
组装 Golang 和 Python 配备 GOPATH 环境变量组装名叫 cgo 的 Golang 包步骤
建立 Golang 项目1
mkdirgolang-python-integration&&cdgolang-python-integration
撰写 Golang wrapper为 Python 部件创建一个 Golang wrapper函数。这将允许您在 Golang 代码中启用 Python 函数。
//mypython.go
packagemain
/
include
staticPyObjectcall_python_function(charfunc_name){
PyObjectpName,pModule,pDict,pFunc,pValue;
pName=PyUnicode_DecodeFSDefault(func_name);
pModule=PyImport_Import(pName);
pDict=PyModule_GetDict(pModule);
pFunc=PyDict_GetItemString(pDict,"my_function");
pValue=PyObject_CallObject(pFunc,NULL);
returnpValue;
}
/
import"C"
import(
"fmt"
"unsafe"
)
funcmain(){
result:=C.call_python_function(C.CString("my_function"))
fmt.Println(C.GoString(result))
}
撰写 Python 模块在 Python 工程中建立 my_function 模块。
my_function.py
defmy_function():
return"HellofromPython!"
搭建 Golang 项目应用 cgo 搭建 Golang 项目。它将允许 Golang 程序启用 C 编码,后者又把启用 Python 编码。
gobuild-buildmode=c-shared-omypython.somypython.go
启用 Python 函数在 Golang 代码中,您可以如今启用 Python 函数。
packagemain
import(
"fmt"
"log"
"syscall"
"unsafe"
)
funcmain(){
//Loadthesharedlibrary.
lib,err:=syscall.LoadDLL("mypython.so")
iferr!=nil{
log.Fatal(err)
}
deferlib.Release()
//Getthefunctionpointer.
callPythonFunction,err:=lib.FindProc("call_python_function")
iferr!=nil{
log.Fatal(err)
}
//Callthe Python function.
result,_,err:=callPythonFunction.Call(
uintptr(unsafe.Pointer(syscall.StringBytePtr("my_function"))),
)
iferr!=nil{
log.Fatal(err)
}
//Printtheresult.
fmt.Println(syscall.UTF16ToString(([1<<30]uint16)(unsafe.Pointer(result))[:]))
}
运作
运作 Golang 程序。
gorunmain.go
导出
HellofromPython!
您现在已成功将 Golang 与 Python 集成,并调用了 Python 函数。
以上就是Golang架构如何跟Python集成?的详细内容,大量请关注其他类似文章!