为python编写golang扩展

1.数值类型

python3支持的 c语言类型

参考 https://docs.python.org/3/library/ctypes.html

ctypes typeC typePython type
c_bool_Boolbool (1)
c_charchar1-character bytes object
c_wcharwchar_t1-character string
c_bytecharint
c_ubyteunsigned?charint
c_shortshortint
c_ushortunsigned?shortint
c_intintint
c_uintunsigned?intint
c_longlongint
c_ulongunsigned?longint
c_longlong__int64?or?long?longint
c_ulonglongunsigned?__int64?or?unsigned?long?longint
c_size_tsize_tint
c_ssize_tssize_t?or?Py_ssize_tint
c_floatfloatfloat
c_doubledoublefloat
c_longdoublelong?doublefloat
c_char_pchar?*?(NUL terminated)bytes object or?None
c_wchar_pwchar_t?*?(NUL terminated)string or?None
c_void_pvoid?*int or?None

golang支持的数值类型

参考 https://chai2010.cn/advanced-go-programming-book/ch2-cgo/ch2-03-cgo-types.html

C语言类型CGO类型Go语言类型
charC.charbyte
singed charC.scharint8
unsigned charC.ucharuint8
shortC.shortint16
unsigned shortC.ushortuint16
intC.intint32
unsigned intC.uintuint32
longC.longint32
unsigned longC.ulonguint32
long long intC.longlongint64
unsigned long long intC.ulonglonguint64
floatC.floatfloat32
doubleC.doublefloat64
size_tC.size_tuint

python 和 golang的数据类型对应

ctypes typeC typePython typeCGO类型Go语言类型
c_charchar1-character bytes objectC.charbyte
c_ubyteunsigned?charintC.ucharuint8
c_shortshortintC.shortint16
c_ushortunsigned?shortintC.ushortuint16
c_intintintC.intint32
c_uintunsigned?intintC.uintuint32
c_longlongintC.longint32
c_ulongunsigned?longintC.ulonguint32
c_longlong__int64?or?long?longintC.longlongint64
c_ulonglongunsigned?__int64?or?unsigned?long?longintC.ulonglonguint64
c_size_tsize_tintC.size_tuint
c_floatfloatfloatC.floatfloat32
c_doubledoublefloatC.doublefloat64

2.编写golang文件

test.go

// libadd.go
package main

import "C" //声明使用了 cgo ,这样才能编写出 C 兼容的动态链接库

// 需要在 Add() 函数上加 //export Add 注释,告诉编译器,Add() 可以供其他程序调用
//export Add
func Add(a, b int) int {
    return a + b
}

//export AddFloat
func AddFloat(a, b float64) float64 {
    return a + b
}

func main(){}

编译dll

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

3.在python文件中调用扩展

test.py

import ctypes

lib = ctypes.cdll.LoadLibrary('./test.dll')

lib.AddFloat.argtypes = [ctypes.c_double, ctypes.c_double]
lib.AddFloat.restype = ctypes.c_double

result = lib.AddFloat(100, 200)
print(result)

result = lib.Add(100, 200)
print(result)

输出:

>python test.py
300.0
300
© Licensed under CC BY-NC-SA 4.0

通往地狱的路,都是由善意铺成的——哈耶克

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!