Python ctypes
跳转到导航
跳转到搜索
加载
from ctypes import *
sort = CDLL('./sort.so') # 这里必须写路径,不然会到系统默认目录去找
注意:C++ 函数需要使用 extern "C" 来包含其声明。
结构体
建一个结构体类型
struct RecType {
int key;
char[10] data;
};
class RecType(Structure):
_fields_ = [('key', c_int), ('data', c_char * 10)]
# 构建一个 RecType 结构体对象
r = RecType(0, 'test')
数组
构建数组对象:
RecArray = RecType * 10
调用 C 函数,需要使用 byref 来传递数组或者结构体对象:
sort.BubbleSort(byref(a), c_int(10)) # a 是前边的 RecArray 类型
指针
NULL 指针
null_ptr = POINTER(c_int)()
函数参数与返回值
要指定参数类型,设置 argtypes 属性为类型的序列;要指定返回值类型,设置 restype 属性为相应的类型。示例:
>>> strchr.restype = c_char_p >>> strchr.argtypes = [c_char_p, c_char] >>> strchr(b"abcdef", b"d") 'def'
库中的变量
使用 string_at 来获取指定地址的数据(不仅仅是 C 字符串),如
#获取整型数据
rl_point = struct.unpack('I', ctypes.string_at(rllib.rl_point, 4))[0]
修改内建对象
使用 ctypes 可以修改 Python 的内建对象:
import ctypes
ctypes.pythonapi.PyObject_GenericSetAttr(
ctypes.py_object(list),
ctypes.py_object('追加'),
ctypes.py_object(list.append))
一个列表 = [1, 2]
一个列表.追加(3)
Ojects/typeobject.c:6370 :
if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
PyErr_Format(
PyExc_TypeError,
"can't set attributes of built-in/extension type '%s'",
type->tp_name);
return -1;
}
这样做不适合于多解释器的情况。