在前一篇文章中,我介绍了 六个 python 解释器。在大多数系统上,cpython 是默认的解释器,而且根据民意调查显示,它还是最流行的解释器。cpython 的独有功能是使用扩展 api 用 c 语言编写 python 模块。用 c 语言编写 python 模块允许你将计算密集型代码转移到 c,同时保留 python 的易用性。
在本文中,我将向你展示如何编写一个 c++ 扩展模块。使用 c++ 而不是 c,因为大多数编译器通常都能理解这两种语言。我必须提前说明缺点:以这种方式构建的 python 模块不能移植到其他解释器中。它们只与 cpython 解释器配合工作。因此,如果你正在寻找一种可移植性更好的与 c 语言模块交互的方式,考虑下使用 ctypes 模块。
源代码和往常一样,你可以在 github 上找到相关的源代码。仓库中的 c++ 文件有以下用途:
my_py_module.cpp: python 模块mymodule 的定义my_cpp_class.h: 一个头文件 - 只有一个暴露给 python 的 c++ 类my_class_py_type.h/cpp: python 形式的 c++ 类pydbg.cpp: 用于调试的单独应用程序本文构建的 python 模块不会有任何实际用途,但它是一个很好的示例。
构建模块在查看源代码之前,你可以检查它是否能在你的系统上编译。我使用 cmake 来创建构建的配置信息,因此你的系统上必须安装 cmake。为了配置和构建这个模块,可以让 python 去执行这个过程:
$ python3 setup.py build
或者手动执行:
$ cmake -b build$ cmake --build build
之后,在 /build 子目录下你会有一个名为 mymodule. so 的文件。
定义扩展模块首先,看一下 my_py_module.cpp 文件,尤其是 pyinit_mymodule 函数:
pymodinit_funcpyinit_mymodule(void) {pyobject* module = pymodule_create(&my_module);pyobject *myclass = pytype_fromspec(&spec_myclass);if (myclass == null){return null;}py_incref(myclass);if(pymodule_addobject(module, myclass, myclass) < 0){py_decref(myclass);py_decref(module);return null;}return module;}
这是本例中最重要的代码,因为它是 cpython 的入口点。一般来说,当一个 python c 扩展被编译并作为共享对象二进制文件提供时,cpython 会在同名二进制文件中(.so)搜索 pyinit_ 函数,并在试图导入时执行它。
无论是声明还是实例,所有 python 类型都是 pyobject 的一个指针。在此函数的第一部分中,module 通过 pymodule_create(...) 创建的。正如你在 module 详述(my_py_module,同名文件)中看到的,它没有任何特殊的功能。
之后,调用 pytype_fromspec 为自定义类型 myclass 创建一个 python 堆类型 定义。一个堆类型对应于一个 python 类,然后将它赋值给 mymodule 模块。
注意,如果其中一个函数返回失败,则必须减少以前创建的复制对象的引用计数,以便解释器删除它们。
指定 python 类型myclass 详述在 my_class_py_type.h 中可以找到,它作为 pytype_spec 的一个实例:
static pytype_spec spec_myclass = {myclass,// namesizeof(myclassobject) + sizeof(myclass),// basicsize0,// itemsizepy_tpflags_default | py_tpflags_basetype, // flagsmyclass_slots // slots};
它定义了一些基本类型信息,它的大小包括 python 表示的大小(myclassobject)和普通 c++ 类的大小(myclass)。myclassobject 定义如下:
typedef struct {pyobject_headint m_value;myclass*m_myclass;} myclassobject;
python 表示的话就是 pyobject 类型,由 pyobject_head 宏和其他一些成员定义。成员 m_value 视为普通类成员,而成员 m_myclass 只能在 c++ 代码内部访问。
pytype_slot 定义了一些其他功能:
static pytype_slot myclass_slots[] = {{py_tp_new, (void*)myclass_new},{py_tp_init,(void*)myclass_init},{py_tp_dealloc, (void*)myclass_dealloc},{py_tp_members, myclass_members},{py_tp_methods, myclass_methods},{0, 0} /* sentinel */};
在这里,设置了一些初始化和析构函数的跳转,还有普通的类方法和成员,还可以设置其他功能,如分配初始属性字典,但这是可选的。这些定义通常以一个哨兵结束,包含 null 值。
要完成类型详述,还包括下面的方法和成员表:
static pymethoddef myclass_methods[] = {{addone, (pycfunction)myclass_addone, meth_noargs,pydoc_str(return an incrmented integer)},{null, null} /* sentinel */};static struct pymemberdef myclass_members[] = {{value, t_int, offsetof(myclassobject, m_value)},{null} /* sentinel */};
在方法表中,定义了 python 方法 addone,它指向相关的 c++ 函数 myclass_addone。它充当了一个包装器,它在 c++ 类中调用 addone() 方法。
在成员表中,只有一个为演示目的而定义的成员。不幸的是,在 pymemberdef 中使用的 offsetof 不允许添加 c++ 类型到 myclassobject。如果你试图放置一些 c++ 类型的容器(如 std::optional),编译器会抱怨一些内存布局相关的警告。
初始化和析构myclass_new 方法只为 myclassobject 提供一些初始值,并为其类型分配内存:
pyobject *myclass_new(pytypeobject *type, pyobject *args, pyobject *kwds){std::cout
实际的初始化发生在 myclass_init 中,它对应于 python 中的 __init__() 方法:
int myclass_init(pyobject *self, pyobject *args, pyobject *kwds){((myclassobject *)self)->m_value = 123;myclassobject* m = (myclassobject*)self;m->m_myclass = (myclass*)pyobject_malloc(sizeof(myclass));if(!m->m_myclass){pyerr_setstring(pyexc_runtimeerror, memory allocation failed);return -1;}try {new (m->m_myclass) myclass();} catch (const std::exception& ex) {pyobject_free(m->m_myclass);m->m_myclass = null;m->m_value = 0;pyerr_setstring(pyexc_runtimeerror, ex.what());return -1;} catch(...) {pyobject_free(m->m_myclass);m->m_myclass = null;m->m_value = 0;pyerr_setstring(pyexc_runtimeerror, initialization failed);return -1;}return 0;}
如果你想在初始化过程中传递参数,必须在此时调用 pyarg_parsetuple。简单起见,本例将忽略初始化过程中传递的所有参数。在函数的第一部分中,pyobject 指针(self)被强转为 myclassobject 类型的指针,以便访问其他成员。此外,还分配了 c++ 类的内存,并执行了构造函数。
注意,为了防止内存泄漏,必须仔细执行异常处理和内存分配(还有释放)。当引用计数将为零时,myclass_dealloc 函数负责释放所有相关的堆内存。在文档中有一个章节专门讲述关于 c 和 c++ 扩展的内存管理。
包装方法从 python 类中调用相关的 c++ 类方法很简单:
pyobject* myclass_addone(pyobject *self, pyobject *args){assert(self);myclassobject* _self = reinterpret_cast(self);unsigned long val = _self->m_myclass->addone();return pylong_fromunsignedlong(val);}
同样,pyobject 参数(self)被强转为 myclassobject 类型以便访问 m_myclass,它指向 c++ 对应类实例的指针。有了这些信息,调用 addone() 类方法,并且结果以 python 整数对象 返回。
3 种方法调试出于调试目的,在调试配置中编译 cpython 解释器是很有价值的。详细描述参阅 官方文档。只要下载了预安装的解释器的其他调试符号,就可以按照下面的步骤进行操作。
gnu 调试器当然,老式的 gnu 调试器(gdb) 也可以派上用场。源码中包含了一个 gdbinit 文件,定义了一些选项和断点,另外还有一个 gdb.sh 脚本,它会创建一个调试构建并启动一个 gdb 会话:
gnu 调试器(gdb)对于 python c 和 c++ 扩展非常有用
gdb 使用脚本文件 main.py 调用 cpython 解释器,它允许你轻松定义你想要使用 python 扩展模块执行的所有操作。
c++ 应用另一种方法是将 cpython 解释器嵌入到一个单独的 c++ 应用程序中。可以在仓库的 pydbg.cpp 文件中找到:
int main(int argc, char *argv[], char *envp[]){py_setprogramname(ldbgpythoncppextension);py_initialize();pyobject *pmodule = pyimport_importmodule(mymodule);if (!pmodule) {pyerr_print();std::cerr << failed to import module mymodule << std::endl;return -1;}pyobject *myclasstype = pyobject_getattrstring(pmodule, myclass);if (!myclasstype) {std::cerr << unable to get type myclass from mymodule << std::endl;return -1;}pyobject *myclassinstance = pyobject_callobject(myclasstype, null);if (!myclassinstance) {std::cerr << instantioation of myclass failed << std::endl;return -1;}py_decref(myclassinstance); // invoke deallocationreturn 0;}
使用 高级接口,可以导入扩展模块并对其执行操作。它允许你在本地 ide 环境中进行调试,还能让你更好地控制传递或来自扩展模块的变量。
缺点是创建一个额外的应用程序的成本很高。
vscode 和 vscodium lldb 扩展使用像 codelldb 这样的调试器扩展可能是最方便的调试选项。仓库包含了一些 vscode/vscodium 的配置文件,用于构建扩展,如 task.json、cmake tools 和调用调试器(launch.json)。这种方法结合了前面几种方法的优点:在图形 ide 中调试,在 python 脚本文件中定义操作,甚至在解释器提示符中动态定义操作。
vscodium 有一个集成的调试器。
用 c++ 扩展 pythonpython 的所有功能也可以从 c 或 c++ 扩展中获得。虽然用 python 写代码通常认为是一件容易的事情,但用 c 或 c++ 扩展 python 代码是一件痛苦的事情。另一方面,虽然原生 python 代码比 c++ 慢,但 c 或 c++ 扩展可以将计算密集型任务提升到原生机器码的速度。
你还必须考虑 abi 的使用。稳定的 abi 提供了一种方法来保持旧版本 cpython 的向后兼容性,如 文档 所述。
最后,你必须自己权衡利弊。如果你决定使用 c 语言来扩展 python 中的一些功能,你已经看到了如何实现它。
以上就是为 python 写一个 c++ 扩展模块的详细内容。
