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

上一篇:283. 移动零


下一篇:算法学习