python调用go

2021/9/18 14:36:12

本文主要是介绍python调用go,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

shared.go

package main

import "C"

//export add
func add(a, b int) int {
    return a + b
}

//export append_str
func append_str(a, b *C.char) *C.char {
    merge := C.GoString(a) + C.GoString(b)
    return C.CString(merge)
}

//go build -buildmode=c-shared -o demo.so shared.go
func main() {
}

python

# https://www.cxyzjd.com/article/weixin_37989267/108869265
import ctypes

lib = ctypes.cdll.LoadLibrary('/home/xxx/projects/golang/demo/demo.so')

result = lib.add(2020, 1)
print(result)

# 调用go模块
go_append_str = lib.append_str

# 显式声明参数和返回的期望类型
go_append_str.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
go_append_str.restype = ctypes.c_char_p
result_bytes = go_append_str("测试".encode("utf-8"),'数据'.encode("utf-8"))
result = result_bytes.decode("utf-8")
print(result)


这篇关于python调用go的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程