Python与C混合编程!是Python和C都不具备的超能力!

小编 2026-06-09 阅读:662 评论:0
    编写 c => python 的接口文件 // vectory_py.c extern \"C\" { vector<point_t>* new_vector()...

\"Python与C混合编程!是Python和C都不具备的超能力!\"

 

\"Python与C混合编程!是Python和C都不具备的超能力!\"

 

编写 c => python 的接口文件

// vectory_py.c
extern \"C\" {
 vector<point_t>* new_vector(){
 return new vector<point_t>;
 }
 void delete_vector(vector<point_t>* v){
 cout << \"destructor called in C++ for \" << v << endl;
 delete v;
 }
 int vector_size(vector<point_t>* v){
 return v->size();
 }
 point_t vector_get(vector<point_t>* v, int i){
 return v->at(i);
 }
 void vector_push_back(vector<point_t>* v, point_t i){
 v->push_back(i);
 }
}

编译: gcc -fPIC -shared -lpython3.6m -o vector_py.so vectory_py.c

\"Python与C混合编程!是Python和C都不具备的超能力!\"

 

编写 ctypes 类型文件

from ctypes import *
class c_point_t(Structure):
 _fields_ = [(\"x\", c_int), (\"y\", c_int)]
class Vector(object):
 lib = cdll.LoadLibrary(\'./vector_py_lib.so\') # class level loading lib
 lib.new_vector.restype = c_void_p
 lib.new_vector.argtypes = []
 lib.delete_vector.restype = None
 lib.delete_vector.argtypes = [c_void_p]
 lib.vector_size.restype = c_int
 lib.vector_size.argtypes = [c_void_p]
 lib.vector_get.restype = c_point_t
 lib.vector_get.argtypes = [c_void_p, c_int]
 lib.vector_push_back.restype = None
 lib.vector_push_back.argtypes = [c_void_p, c_point_t]
 lib.foo.restype = None
 lib.foo.argtypes = []
 def __init__(self):
 self.vector = Vector.lib.new_vector() # pointer to new vector
 def __del__(self): # when reference count hits 0 in Python,
 Vector.lib.delete_vector(self.vector) # call C++ vector destructor
 def __len__(self):
 return Vector.lib.vector_size(self.vector)
 def __getitem__(self, i): # access elements in vector at index
 if 0 <= i < len(self):
 return Vector.lib.vector_get(self.vector, c_int(i))
 raise IndexError(\'Vector index out of range\')
 def __repr__(self):
 return \'[{}]\'.format(\', \'.join(str(self[i]) for i in range(len(self))))
 def push(self, i): # push calls vector\'s push_back
 Vector.lib.vector_push_back(self.vector, i)
 def foo(self): # foo in Python calls foo in C++
 Vector.lib.foo(self.vector)

然后才是调用

from vector import *
a = Vector()
b = c_point_t(10, 20)
a.push(b)
a.foo()
for i in range(len(a)) :
 print(a[i].x)
 print(a[i].y)

为Python写扩展

完成上述的操作后,我头很大,很难想象当项目稍微修改后,我们要跟随变化的代码量有多大!于是换了一种思路,为Python写扩展。

进群:960410445   有惊喜大礼包!

安装Python开发包

yum install -y python36-devel

修改数据交互文件

#include <python3.6m/Python.h>
PyObject* foo()
{
 PyObject* result = PyList_New(0);
 int i = 0, j = 0;
 for (j = 0; j < 2; j++) {
 PyObject* sub = PyList_New(0);
 for (i = 0; i < 100; ++i)
 {
 PyList_Append(sub, Py_BuildValue(\"{s:i, s:i}\", \"x\", i, \"y\", 100 - i));
 }
 PyList_Append(result, sub);
 }
 return result;
}

调用

from ctypes import *
lib = cdll.LoadLibrary(\'./extlist.so\') # class level loading lib
lib.foo.restype = py_object
b = lib.foo()
for i in range(len(b)) :
 for j in range(len(b[i])) :
 d = b[i][j]
 print(d[\'x\'])

很显然,第二种方式中,我已经封装了很复杂的结构了,如果用 c++ 来表示的话,将是:

vector<vector >

遇到的问题

Python C 混编时 Segment

这个问题困扰了我有一段时间,开始一直在纠结是代码哪错了,后来恍然大悟,Python 和 C 的堆栈是完全不同的,而当我在交互大量数据的时候,Python GC 可能会把 C 的内存当作未使用,直接给释放了(尤其是上述第二种方案),这就是问题所在。(Python GC 中使用的代龄后续专门开文章来说明,欢迎关注公众号 cn_isnap)

这里的解决方案其实有很多,内存能撑过Python前两代的检查就可了,或者是纯C管理。在这里我推荐一种粗暴的解决方案:

对于任何调用Python对象或Python C API的C代码,确保你首先已经正确地获取和释放了GIL。 这可以用 PyGILState_Ensure() 和 PyGILState_Release() 来做到,如下所示:

...
/* Make sure we own the GIL */
PyGILState_STATE state = PyGILState_Ensure();
/* Use functions in the interpreter */
...
/* Restore previous GIL state and return */
PyGILState_Release(state);
版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
标签列表