项目中要对一个用 C 编写的 .so 库进行逻辑自测。这项工做,考虑到灵活性,我首先考虑用 Python 来完成。html
研究了一些资料,采用 python 的 ctypes
来完成这项工做。已经验证经过,本文记录一下适配流程。验证采用 cpp 来设计,不过暂时尚未涉及类的内容。之后若是须要再补足。python
本文地址:http://www.javashuo.com/article/p-phcrhasr-mm.htmllinux
如下资料是关于 ctypes
的,也就是本文采用的资料:git
因为研究 ctypes
时我用的是 Python 2.7,后来切换到 Python 3 的时候稍微遇到一点适配问题,所以也顺便记录一下我切换过程当中参考的一些资料:github
Python 调用 C 还有其余的几个解决方案,好比 cython
、SWIG
等等。可是查了很多资料没能解决个人两个关键诉求(结构体参数和回调函数):segmentfault
使用 ctypes,须要首先安装 python-dev 包:centos
Ubuntu: $ sudo apt-get install python-dev -y CentOS: $ sudo yum install python-devel -y
这里主要包含了 ctypes
包。数组
将你的 C 代码编译成 .so 文件。这里假设目标文件是 libtest.so
,放在工做目录下。多线程
首先是最简单的函数调用,而且函数参数为基本数据类型。待调用的函数定义以下:函数
extern "C" int max(int a, int b) { return (a > b) ? a : b; }
这种状况下,在 Python 中的调用就很简单了。咱们须要使用 ctypes
包中的 cdll
模块加载 .so
文件,而后就能够调用库中的函数了。
Python 代码以下:
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from ctypes import * so_file = cdll.LoadLibrary('./libtest.so') # 若是前文使用的是 import ctypes,则这里应该是 ctypes.cdll.LoadLobrary(...) ret = so_file.max(22, 20) print('so_file class:', type(so_file)) print('so_file.max =', ret)
输出:
so_file class: <class 'ctypes.CDLL'> so_file.max = 22
这就稍微复杂点了,由于 C 语言中的结构体在 Python 中并无直接一一对应。不过不用担忧,简单而言,解决方案就是:在 Python 代码中调用 ctypes
的类进行 Python 化的封装。
网上的代码进行了最简化的演示,这里我从这一小节开始,建议读者把一个 .so 文件,封装成 Python 模块。这样一来库的包装更加简洁和清晰。
这里是 C 代码的部分,主要是结构体的声明。用于示例的函数很简单,只是一个 print 功能而已:
typedef struct _test_struct { int integer; char * c_str; void * ptr; int array[8]; } TestStruct_st; extern "C" const char *print_test_struct(TestStruct_st *pTestSt) { if (NULL == pTestSt) { return "C -- parameter NULL"; # "C --" 打头区分这是在 .so 里面输出的 } printf("C -- {\n"); printf("C -- \tinteger : %d\n", pTestSt->integer); printf("C -- \tcstr : %s\n", pTestSt->c_str); printf("C -- \tptr : %p\n", pTestSt->ptr); printf("C -- \tarray : ["); for (int tmp = 0; tmp < 7; tmp ++) { printf("%d, ", pTestSt->array[tmp]); } printf("%d]\n", pTestSt->array[7]); printf("C -- }\n"); return "success"; }
首先,咱们要对结构体进行转换:
from ctypes import * INTARRAY8 = c_int * 8 class PyTestStruct(Structure): 'TestStruct_st 的 Python 版本' _fields_ = [ ("integer", c_int), ("c_str", c_char_p), ("ptr", c_void_p), ("array", INTARRAY8) ]
首先对结构体里的 int 数组进行了重定义,也就是 INTARRAY8
。
接着,注意一下 _fields_
的内容:这里就是对 C 数据类型的转换。左边是 C 的结构成员名称,右边则是在 python 中声明一下各个成员的类型。其余的一些类型请参见官方文档。
此外还须要注意一下相似于 c_int
, c_void_p
等等的定义是在 ctypes
中的,若是是用 impoer ctypes
的方式包含 ctypes 模块,则应该写成 ctypes.c_int
, ctypes.c_void_p
。
第三个要注意的是:这个类必须定义为 ctypes.Structure
的子类,不然在进行后续的函数传递时,ctypes
因为不知道如何进行数据类型的对应,会抛出异常
class testdll: '用于 libtest.so 的加载,包含了 cdll 对象' def __init__(self): self.cdll = cdll.LoadLibrary('./libtest.so') # 直接加载 .so 文件。感受更好的方式是写成单例 return def print_test_struct(self, test_struct): func = self.cdll.print_test_struct func.restype = c_char_p func.argtypes = [POINTER(PyTestStruct)] return func(byref(test_struct)).decode()
注意最后一句 func(byref(test_struct))
中的 byref
。这个函数能够看成是 C 中的取地址符 &
的 Python 适配。由于函数参数是一个结构体指针(地址),所以咱们须要用上 byref
函数。
直接上 Python 代码,很短的(import 语句就不用写了吧,读者自行发挥就好):
test_struct = PyTestStruct() test_struct.integer = 1 test_struct.c_str = 'Hello, C'.encode() # Python 2.x 则不须要写 encode test_struct.ptr = 0xFFFFFFFF test_struct.array = INTARRAY8() for i in range(0, len(test_struct.array)): j = i + 1 test_struct.array[i] = j * 10 + j so_file = testdll() test_result = so_file.print_test_struct(test_struct) print('test_result:', test_result)
执行结果:
C -- { C -- integer : 1 C -- cstr : Hello, C C -- ptr : 0xffffffff C -- array : [11, 22, 33, 44, 55, 66, 77, 88] C -- } test_result: success
这里能够看到,结构体参数的准备仍是很简单的,就是将用 Python 适配过来以后的类中对应名字的成员进行赋值就行了。
注意一下在 Python 3.x 中,str
和 bytes
类型是区分开的,而 char *
对应的是后者,所以须要进行 encode / decode 转换。在 Python 2.x 则不须要。
这个主题就稍微绕一些了,也就是说在 C 接口中,须要传入回调函数做为参数。这个问题在 Python 中也能够解决,而且回调函数能够用 Python 定义。
C 代码很简单:回调函数的传入参数为 int
,返回参数也是 int
。C 代码获取一个随机数交给回调去处理。
extern "C" void print_given_num(int (*callback)(int)) { if (NULL == callback) { printf("C -- No number given\n"); } static int s_isInit = 0; if (0 == s_isInit) { s_isInit = 1; srand(time(NULL)); } int num = callback((int)rand()); printf("C -- given num by callback: %d (0x%x)\n", num, num); return; }
这里我仍是用前面的 testdll
类来封装:
class testdll: '用于 libtest.so 的加载,包含了 cdll 对象' def __init__(self): self.cdll = cdll.LoadLibrary('./libtest.so') return def print_given_num(self, callback): self.cdll.print_given_num(callback) return testCallbackType = CFUNCTYPE(None, c_int, c_int)
最后的 testCallbackType
经过 ctypes
定义了一个回调函数类型,这个在后面的调用中须要使用
在 CFUNCTYPE
后面的第一个参数为 None
,这表示回调函数的返回值类型为 void
回调函数用 Python 完成,注意接受的参数和返回数据类型都应该与 .so 中的定义一致。我这里的回调函数中,将 .so 传过来的参数取了一个最低字节返回:
def _callback(para): print('get callback req:', hex(para)) print('return:', hex(para & 0xFF)) return para & 0xFF
so_file = testdll() cb = testCallbackType(_callback) so_file.print_given_num(cb)
执行结果:
get callback req: 0x4f770b3a return: 0x3a C -- given num by callback: 58 (0x3a)
怎么样,是否是以为很简单?