百度安全验证https://baijiahao.baidu.com/s?id=1718727685871848121&wfr=spider&for=pcpython调用go或c语言_小小明-代码实体的博客-CSDN博客_python 调用go
chongchong.go:
package main
import (
"C" //C必须导入
"fmt"
"math"
"sort"
"sync"
)
var count int
var mtx sync.Mutex
//export Add
func Add(a, b int) int {
// 必须通过export函数名格式的注释申明该函数可以被外部接口
return a + b
}
//export Cosine
func Cosine(x float64) float64 {
return math.Cos(x)
}
//export Sort
func Sort(vals []int) {
sort.Ints(vals)
}
func SortPtr(vals *[]int) {
Sort(*vals)
}
//export Log
func Log(msg string) int {
mtx.Lock()
defer mtx.Unlock()
fmt.Println(msg)
count++
return count
}
func LogPtr(msg *string) int {
return Log(*msg)
}
//main函数中什么都不要写,和包名main要对应
func main() {}
执行 go build -o chongchong.so -buildmode=c-shared chonghcong.go
完成后,编译器输出两个文件,一个是C头文件chonghcong.h,另一个为chonghcong.so共享对象文件:
-rw-rw-r-- 1 1779 Dec 9 15:50 chongchong.h
-rw-rw-r-- 1 3748095 Dec 9 15:50 chongchong.so
然后执行file chongchong.so,得到:
chongchong.so: Mach-O 64-bit dynamically linked shared library x86_64
下面以python调用共享库为例:
from __future__ import print_function
# 用ctypes库调用导出的Go函数
from ctypes import *
# lib变量表示从共享目标文件加载的符号
lib = cdll.LoadLibrary("./chongchong.so")
lib.Add.argtypes = [c_longlong, c_longlong]
lib.Add.restype = c_longlong
print("chongchong.Add(12,99) = %d" % lib.Add(12,99))
lib.Cosine.argtypes = [c_double]
lib.Cosine.restype = c_double
print("chongchong.Cosine(1) = %f" % lib.Cosine(1))
# Python类 GoString和 GoSlice映射到它们各自的 C 结构类型
class GoSlice(Structure):
_fields_ = [("data", POINTER(c_void_p)), ("len", c_longlong), ("cap", c_longlong)]
nums = GoSlice((c_void_p * 5)(74, 4, 122, 9, 12), 5, 5)
lib.Sort.argtypes = [GoSlice]
lib.Sort.restype = None
lib.Sort(nums)
print("chongchong.Sort(74,4,122,9,12) = %s" % [nums.data[i] for i in range(nums.len)])
class GoString(Structure):
_fields_ = [("p", c_char_p), ("n", c_longlong)]
lib.Log.argtypes = [GoString]
lib.Log.restype = c_longlong
msg = GoString(b"Hello Python!", 13)
print("chongchong.Log(msg) = %s" % lib.Log(msg))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)