专栏名称: Python学习交流
每天更新,更新python相关的知识。希望诸君有所收获!
目录
相关文章推荐
Python爱好者社区  ·  史上最强!PINN杀疯了 ·  昨天  
Python爱好者社区  ·  英伟达憾失DeepSeek关键人才?美国放走 ... ·  昨天  
Python爱好者社区  ·  离谱!下载DeepSeek最高判刑20年? ·  2 天前  
Python爱好者社区  ·  1885页的Python完全版电子书 ·  3 天前  
Python开发者  ·  o3-mini 碾压 DeepSeek ... ·  5 天前  
51好读  ›  专栏  ›  Python学习交流

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

Python学习交流  · 公众号  · Python  · 2018-12-17 14:43

正文



编写 c => python 的接口文件

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

编译: gcc -fPIC -shared -lpython3.6m -o vector_py.so vectory_py.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写扩展。

私信菜鸟007有惊喜大礼包!

安装Python开发包

yum install -y python36-devel

修改数据交互文件

#include 
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






请到「今天看啥」查看全文