Python实例浅谈之三Python与C/C++相互调用
一、问题
Python 模块和 C/C++ 的动态库间相互调用在实际的应用中会有所涉及,在此作一总结。
二、Python 调用 C/C++
1、Python 调用 C 动态链接库
Python 调用 C 库比较简单,不经过任何封装打包成 so,再使用 python 的 ctypes 调用即可。
(1)C 语言文件:pycall.c
/***gcc -o libpycall.so -shared -fPIC pycall.c*/ #include <stdio.h> #include <stdlib.h> int foo(int a, int b) { printf("you input %d and %d\n", a, b); return a+b; }
(2)gcc 编译生成动态库 libpycall.so:gcc -o libpycall.so -shared -fPIC pycall.c。使用 g++ 编译生成 C 动态库的代码中的函数或者方法时,需要使用 extern "C" 来进行编译。
(3)Python 调用动态库的文件:pycall.pyimport ctypes ll = ctypes.cdll.LoadLibrary lib = ll("./libpycall.so") lib.foo(1, 3) print '***finish***'
(4)运行结果:
2、Python 调用 C++(类) 动态链接库
需要 extern "C" 来辅助,也就是说还是只能调用 C 函数,不能直接调用方法,但是能解析 C++ 方法。不是用 extern "C",构建后的动态链接库没有这些函数的符号表。
(1)C++ 类文件:pycallclass.cpp
3、Python 调用 C/C++ 可执行程序
(1)C/C++ 程序:main.cpp
import commands import os main = "./testmain" if os.path.exists(main): rc, out = commands.getstatusoutput(main) print 'rc = %d, \nout = %s' % (rc, out)print '*'*10
f = os.popen(main)
data = f.readlines()
f.close()
print dataprint '*'*10
os.system(main)
(4)运行结果:
4、扩展 Python(C++ 为 Python 编写扩展模块)
所有能被整合或导入到其它 python 脚本的代码,都可以被称为扩展。可以用 Python 来写扩展,也可以用 C 和 C++ 之类的编译型的语言来写扩展。Python 在设计之初就考虑到要让模块的导入机制足够抽象。抽象到让使用模块的代码无法了解到模块的具体实现细节。Python 的可扩展性具有的优点:方便为语言增加新功能、具有可定制性、代码可以实现复用等。为 Python 创建扩展需要三个主要的步骤:创建应用程序代码、利用样板来包装代码和编译与测试。
(1)创建应用程序代码
#include <stdio.h> #include <stdlib.h> #include <string.h>int fac(int n)
{
if (n < 2) return(1); / 0! == 1! == 1 /
return (n)fac(n-1); / n! == n*(n-1)! */
}char reverse(char s)
{
register char t, / tmp /
p = s, / fwd /
q = (s + (strlen(s) - 1)); / bwd /<span style="color: rgba(0, 0, 255, 1)">while</span> (p < q) <span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)"> if p < q </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)"> { t </span>= *p; <span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)"> swap & move ptrs </span><span style="color: rgba(0, 128, 0, 1)">*/</span> *p++ = *<span style="color: rgba(0, 0, 0, 1)">q; </span>*q-- =<span style="color: rgba(0, 0, 0, 1)"> t; } </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)">(s);
}
int main()
{
char s[BUFSIZ];
printf("4! == %d\n", fac(4));
printf("8! == %d\n", fac(8));
printf("12! == %d\n", fac(12));
strcpy(s, "abcdef");
printf("reversing 'abcdef', we get '%s'\n", \
reverse(s));
strcpy(s, "madam");
printf("reversing 'madam', we get '%s'\n", \
reverse(s));
return 0;
}
上述代码中有两个函数,一个是递归求阶乘的函数 fac();另一个 reverse() 函数实现了一个简单的字符串反转算法,其主要目的是修改传入的字符串,使其内容完全反转,但不需要申请内存后反着复制的方法。
(2)用样板来包装代码接口的代码被称为“样板”代码,它是应用程序代码与 Python 解释器之间进行交互所必不可少的一部分。样板主要分为 4 步:a、包含 Python 的头文件;b、为每个模块的每一个函数增加一个型如 PyObject* Module_func()的包装函数;c、为每个模块增加一个型如 PyMethodDef ModuleMethods[] 的数组;d、增加模块初始化函数 void initModule()。
从 Python 到 C 的转换用 PyArg_Parse* 系列函数,int PyArg_ParseTuple():把 Python 传过来的参数转为 C;int PyArg_ParseTupleAndKeywords() 与 PyArg_ParseTuple()作用相同,但是同时解析关键字参数;它们的用法跟 C 的 sscanf 函数很像,都接受一个字符串流,并根据一个指定的格式字符串进行解析,把结果放入到相应的指针所指的变量中去,它们的返回值为 1 表示解析成功,返回值为 0 表示失败。从 C 到 Python 的转换函数是 PyObject* Py_BuildValue():把 C 的数据转为 Python 的一个对象或一组对象,然后返回之;Py_BuildValue 的用法跟 sprintf 很像,把所有的参数按格式字符串所指定的格式转换成一个 Python 的对象。
C 与 Python 之间数据转换的转换代码:
为每个模块增加一个型如 PyMethodDef ModuleMethods[] 的数组,以便于 Python 解释器能够导入并调用它们,每一个数组都包含了函数在 Python 中的名字,相应的包装函数的名字以及一个 METH_VARARGS 常量,METH_VARARGS 表示参数以 tuple 形式传入。 若需要使用 PyArg_ParseTupleAndKeywords() 函数来分析命名参数的话,还需要让这个标志常量与 METH_KEYWORDS 常量进行逻辑与运算常量 。数组最后用两个 NULL 来表示函数信息列表的结束。
所有工作的最后一部分就是模块的初始化函数,调用 Py_InitModule()函数,并把模块名和 ModuleMethods[] 数组的名字传递进去,以便于解释器能正确的调用模块中的函数。
(3)编译
为了让新 Python 的扩展能被创建,需要把它们与 Python 库放在一起编译,distutils 包被用来编译、安装和分发这些模块、扩展和包。
创建一个 setup.py 文件,编译最主要的工作由 setup() 函数来完成:
测试模块:
(5)引用计数和线程安全
Python 对象引用计数的宏:Py_INCREF(obj) 增加对象 obj 的引用计数,Py_DECREF(obj) 减少对象 obj 的引用计数。Py_INCREF()和 Py_DECREF() 两个函数也有一个先检查对象是否为空的版本,分别为 Py_XINCREF()和 Py_XDECREF()。
编译扩展的程序员必须要注意,代码有可能会被运行在一个多线程的 Python 环境中。这些线程使用了两个 C 宏 Py_BEGIN_ALLOW_THREADS 和 Py_END_ALLOW_THREADS,通过将代码和线程隔离,保证了运行和非运行时的安全性,由这些宏包裹的代码将会允许其他线程的运行。
三、C/C++ 调用 Python
C++ 可以调用 Python 脚本,那么就可以写一些 Python 的脚本接口供 C++ 调用了,至少可以把 Python 当成文本形式的动态链接库,
需要的时候还可以改一改,只要不改变接口。缺点是 C++ 的程序一旦编译好了,再改就没那么方便了。
(1)Python 脚本:pytest.py
#test function def add(a,b): print "in python function add" print "a = " + str(a) print "b = " + str(b) print "ret = " + str(a+b) returndef foo(a):
</span><span style="color: rgba(0, 0, 255, 1)">print</span> <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">in python function foo</span><span style="color: rgba(128, 0, 0, 1)">"</span> <span style="color: rgba(0, 0, 255, 1)">print</span> <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">a = </span><span style="color: rgba(128, 0, 0, 1)">"</span> +<span style="color: rgba(0, 0, 0, 1)"> str(a) </span><span style="color: rgba(0, 0, 255, 1)">print</span> <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">ret = </span><span style="color: rgba(128, 0, 0, 1)">"</span> + str(a *<span style="color: rgba(0, 0, 0, 1)"> a) </span><span style="color: rgba(0, 0, 255, 1)">return</span>
class guestlist:
def init(self):
print "aaaa"
def p():
print "bbbbb"
def getitem(self, id):
return "ccccc"
def update():
guest = guestlist()
print guest['aa']#update()
(2)C++ 代码:
/**g++ -o callpy callpy.cpp -I/usr/include/python2.6 -L/usr/lib64/python2.6/config -lpython2.6**/ #include <Python.h> int main(int argc, char** argv) { // 初始化 Python //在使用 Python 系统前,必须使用 Py_Initialize 对其 //进行初始化。它会载入 Python 的内建模块并添加系统路 //径到模块搜索路径中。这个函数没有返回值,检查系统 //是否初始化成功需要使用 Py_IsInitialized。 Py_Initialize();PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3)); PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 检查初始化是否成功 </span> <span style="color: rgba(0, 0, 255, 1)">if</span> ( !<span style="color: rgba(0, 0, 0, 1)">Py_IsInitialized() ) { </span><span style="color: rgba(0, 0, 255, 1)">return</span> -<span style="color: rgba(128, 0, 128, 1)">1</span><span style="color: rgba(0, 0, 0, 1)">; } </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 添加当前路径 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">把输入的字符串作为Python代码直接运行,返回0 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">表示成功,-1表示有错。大多时候错误都是因为字符串 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">中有语法错误。 </span> PyRun_SimpleString(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">import sys</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); PyRun_SimpleString(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">print '---import sys---'</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); PyRun_SimpleString(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">sys.path.append('./')</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); PyObject </span>*pName,*pModule,*pDict,*pFunc,*<span style="color: rgba(0, 0, 0, 1)">pArgs; </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 载入名为pytest的脚本 </span> pName = PyString_FromString(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">pytest</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); pModule </span>=<span style="color: rgba(0, 0, 0, 1)"> PyImport_Import(pName); </span><span style="color: rgba(0, 0, 255, 1)">if</span> ( !<span style="color: rgba(0, 0, 0, 1)">pModule ) { printf(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">can't find pytest.py</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); getchar(); </span><span style="color: rgba(0, 0, 255, 1)">return</span> -<span style="color: rgba(128, 0, 128, 1)">1</span><span style="color: rgba(0, 0, 0, 1)">; } pDict </span>=<span style="color: rgba(0, 0, 0, 1)"> PyModule_GetDict(pModule); </span><span style="color: rgba(0, 0, 255, 1)">if</span> ( !<span style="color: rgba(0, 0, 0, 1)">pDict ) { </span><span style="color: rgba(0, 0, 255, 1)">return</span> -<span style="color: rgba(128, 0, 128, 1)">1</span><span style="color: rgba(0, 0, 0, 1)">; } </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 找出函数名为add的函数 </span> printf(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">----------------------\n</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); pFunc </span>= PyDict_GetItemString(pDict, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">add</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">if</span> ( !pFunc || !<span style="color: rgba(0, 0, 0, 1)">PyCallable_Check(pFunc) ) { printf(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">can't find function [add]</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); getchar(); </span><span style="color: rgba(0, 0, 255, 1)">return</span> -<span style="color: rgba(128, 0, 128, 1)">1</span><span style="color: rgba(0, 0, 0, 1)">; } </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 参数进栈 </span> *<span style="color: rgba(0, 0, 0, 1)">pArgs; pArgs </span>= PyTuple_New(<span style="color: rgba(128, 0, 128, 1)">2</span><span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> PyObject* Py_BuildValue(char *format, ...) </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 把C++的变量转换成一个Python对象。当需要从 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> C++传递变量到Python时,就会使用这个函数。此函数 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 有点类似C的printf,但格式不同。常用的格式有 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> s 表示字符串, </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> i 表示整型变量, </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> f 表示浮点数, </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> O 表示一个Python对象。 </span>
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 调用Python函数 </span>
PyObject_CallObject(pFunc, pArgs);
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">下面这段是查找函数foo 并执行foo </span> printf(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">----------------------\n</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); pFunc </span>= PyDict_GetItemString(pDict, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">foo</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">if</span> ( !pFunc || !<span style="color: rgba(0, 0, 0, 1)">PyCallable_Check(pFunc) ) { printf(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">can't find function [foo]</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); getchar(); </span><span style="color: rgba(0, 0, 255, 1)">return</span> -<span style="color: rgba(128, 0, 128, 1)">1</span><span style="color: rgba(0, 0, 0, 1)">; } pArgs </span>= PyTuple_New(<span style="color: rgba(128, 0, 128, 1)">1</span><span style="color: rgba(0, 0, 0, 1)">); PyTuple_SetItem(pArgs, </span><span style="color: rgba(128, 0, 128, 1)">0</span>, Py_BuildValue(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">l</span><span style="color: rgba(128, 0, 0, 1)">"</span>,<span style="color: rgba(128, 0, 128, 1)">2</span><span style="color: rgba(0, 0, 0, 1)">)); PyObject_CallObject(pFunc, pArgs); printf(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">----------------------\n</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); pFunc </span>= PyDict_GetItemString(pDict, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">update</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">if</span> ( !pFunc || !<span style="color: rgba(0, 0, 0, 1)">PyCallable_Check(pFunc) ) { printf(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">can't find function [update]</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">); getchar(); </span><span style="color: rgba(0, 0, 255, 1)">return</span> -<span style="color: rgba(128, 0, 128, 1)">1</span><span style="color: rgba(0, 0, 0, 1)">; } pArgs </span>= PyTuple_New(<span style="color: rgba(128, 0, 128, 1)">0</span><span style="color: rgba(0, 0, 0, 1)">); PyTuple_SetItem(pArgs, </span><span style="color: rgba(128, 0, 128, 1)">0</span>, Py_BuildValue(<span style="color: rgba(128, 0, 0, 1)">""</span><span style="color: rgba(0, 0, 0, 1)">)); PyObject_CallObject(pFunc, pArgs); Py_DECREF(pName); Py_DECREF(pArgs); Py_DECREF(pModule); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 关闭Python </span>
Py_Finalize();
return 0;
}
(3)C++ 编译成二进制可执行文件:g++ -o callpy callpy.cpp -I/usr/include/python2.6 -L/usr/lib64/python2.6/config -lpython2.6,编译选项需要手动指定 Python 的 include 路径和链接接路径(Python 版本号根据具体情况而定)。
(4)运行结果:
四、总结
(1)Python 和 C/C++ 的相互调用仅是测试代码,具体的项目开发还得参考 Python 的 API 文档。
(2)两者交互,C++ 可为 Python 编写扩展模块,Python 也可为 C++ 提供脚本接口,更加方便于实际应用。
(3)若有不足,请留言,在此先感谢!