为python编写golang扩展

1.数值类型

python3支持的 c语言类型

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

ctypes type C type Python type
c_bool _Bool bool (1)
c_char char 1-character bytes object
c_wchar wchar_t 1-character string
c_byte char int
c_ubyte unsigned?char int
c_short short int
c_ushort unsigned?short int
c_int int int
c_uint unsigned?int int
c_long long int
c_ulong unsigned?long int
c_longlong __int64?or?long?long int
c_ulonglong unsigned?__int64?or?unsigned?long?long int
c_size_t size_t int
c_ssize_t ssize_t?or?Py_ssize_t int
c_float float float
c_double double float
c_longdouble long?double float
c_char_p char?*?(NUL terminated) bytes object or?None
c_wchar_p wchar_t?*?(NUL terminated) string or?None
c_void_p void?* int or?None

golang支持的数值类型

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

C语言类型 CGO类型 Go语言类型
char C.char byte
singed char C.schar int8
unsigned char C.uchar uint8
short C.short int16
unsigned short C.ushort uint16
int C.int int32
unsigned int C.uint uint32
long C.long int32
unsigned long C.ulong uint32
long long int C.longlong int64
unsigned long long int C.ulonglong uint64
float C.float float32
double C.double float64
size_t C.size_t uint

python 和 golang的数据类型对应

ctypes type C type Python type CGO类型 Go语言类型
c_char char 1-character bytes object C.char byte
c_ubyte unsigned?char int C.uchar uint8
c_short short int C.short int16
c_ushort unsigned?short int C.ushort uint16
c_int int int C.int int32
c_uint unsigned?int int C.uint uint32
c_long long int C.long int32
c_ulong unsigned?long int C.ulong uint32
c_longlong __int64?or?long?long int C.longlong int64
c_ulonglong unsigned?__int64?or?unsigned?long?long int C.ulonglong uint64
c_size_t size_t int C.size_t uint
c_float float float C.float float32
c_double double float C.double float64

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

一个伟大的程序员, 其价值相当于普通程序员的1万倍!——比尔盖茨

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

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