前情提要
在之前的文章Python調用C++之PYBIND11簡介中我們介紹了pybind11的基本用法,我們已經知其然,接下來我們通過代碼分析,知其所以然。通過之前的講解,我們知道使用pybind11去導出C++接口到Python,只要使用一個宏PYBIND11_MODULE
,例如之前的例子,將已有的C++函數int add(int, int)
導出到Python:
#include "existence.h"
#include <pybind11/pybind11.h>
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function which adds two numbers");
}
我們知道,用傳統方法編寫C++擴展模塊的方法主要有以下幾步,對於Python2和Python3,方法略有不同:
Python2
- 擁有一個需要導出到Python的C++接口;
- 將這個C++接口用一個
PyMethodDef
結構體封裝起來,構成一個方法表,如果使用PyModule_AddObject
這一步是不需要的;如果將PyModuleDef
比作車頭,PyMethodDef
比作車廂,兩種方法的區別就相當於是PyModule_AddObject()
先把車廂掛在車頭上在網上裝貨物,而手動封裝PyMethodDef`就是先裝了貨物在將車頭鏈接上; - 調用
Py_InitModule(name, PyMethodDef**)
得到一個模塊對象,假設叫做m
; - 調用
PyModule_AddObject(m, name, PyObject*)
將函數添加到模塊;或者調用Py_InitModule
去裝載第二步中封裝的方法表; - 給出一個按一定規則命名的函數供Python解析器加在該模塊的時候調用,這個函數名的命名規則是
特定前綴 + 模塊名
。Python 2的是init
。例如,initexample
,其中example
是模塊名。作用是調用第四步中的兩個函數之一去盤活整個創建過程。
Python3
- 擁有一個需要導出到Python的C++接口;
- 將這個C++接口用一個
PyMethodDef
結構體封裝起來,構成一個方法表,如果使用PyModule_AddObject()
這一步是不需要的。如果將PyModuleDef
比作車頭,PyMethodDef
比作車廂,兩種方法的區別就相當於是PyModule_AddObject()
先把車廂掛在車頭上在網上裝貨物,而手動封裝PyMethodDef`就是先裝了貨物在將車頭鏈接上; - 將第二步方法表使用
PyModuleDef
結構體封裝; - 根據
PyModuleDef
種的內容初始化模塊,調用PyModule_Create(PyModuleDef*)
函數創建模塊; - 給出一個按一定規則命名的函數供Python解析器加在該模塊的時候調用,這個函數名的命名規則是
特定前綴 + 模塊名
。Python 3 的特定前綴是PyInit_
。例如,PyInit_example
,其中example
是模塊名。
總結就是,一個表示模塊的對象,一個表,表的每一行用來表示模塊擁有的一個方法對象,在模塊初始化的時候,解析器找到一個特殊名字的方法,這個方法負責生成一個模塊對象和填充表格的內容,這兩件事誰先誰後並沒有影響。
相比於使用Python官方介紹的方法,pybind11只用兩三行代碼就完成了工作,簡直不要太爽。關於使用傳統方法去導出C++接口,我在使用C語言編寫Python模塊-引子也有介紹過,沒看過的可以去看一看,它是我們能看懂pybind11源碼的基礎。
正文
萬變不離其宗,pybind11只不過是將原本我們所需要做的封裝好了而已,下面我們就來揭開它神祕的面紗。首先,我們來看看宏PYBIND11_MODULE
定義,它所依賴一些宏我也一併找出並列了出來:
#define PYBIND11_MODULE(name, variable) \
static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
PYBIND11_PLUGIN_IMPL(name) { \
PYBIND11_CHECK_PYTHON_VERSION \
auto m = pybind11::module(PYBIND11_TOSTRING(name)); \
try { \
PYBIND11_CONCAT(pybind11_init_, name)(m); \
return m.ptr(); \
} PYBIND11_CATCH_INIT_EXCEPTIONS \
} \
void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
#define PYBIND11_CONCAT(first, second) first##second
#define PYBIND11_PLUGIN_IMPL(name) \
extern "C" PYBIND11_EXPORT PyObject *PyInit_##name(); \
extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
#define PYBIND11_CHECK_PYTHON_VERSION \
{ \
const char *compiled_ver = PYBIND11_TOSTRING(PY_MAJOR_VERSION) \
"." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
const char *runtime_ver = Py_GetVersion(); \
size_t len = std::strlen(compiled_ver); \
if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
|| (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
PyErr_Format(PyExc_ImportError, \
"Python version mismatch: module was compiled for Python %s, " \
"but the interpreter version is incompatible: %s.", \
compiled_ver, runtime_ver); \
return nullptr; \
} \
}
#define PYBIND11_STRINGIFY(x) #x
#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
#define PYBIND11_CATCH_INIT_EXCEPTIONS \
catch (pybind11::error_already_set &e) { \
PyErr_SetString(PyExc_ImportError, e.what()); \
return nullptr; \
} catch (const std::exception &e) { \
PyErr_SetString(PyExc_ImportError, e.what()); \
return nullptr; \
}
#if !defined(PYBIND11_EXPORT)
# if defined(WIN32) || defined(_WIN32)
# define PYBIND11_EXPORT __declspec(dllexport)
# else
# define PYBIND11_EXPORT __attribute__ ((visibility("default")))
# endif
#endif
這麼看比較晦澀,我們將文章開頭的例子使用進行宏展開,得到下面的代碼,這麼一看,清晰很多:
static void pybind11_init_example(pybind11::module &);
static PyObject *pybind11_init_wrapper();
extern "C" __attribute__ ((visibility("default"))) void initexample();
extern "C" __attribute__ ((visibility("default"))) void initexample() { (void)pybind11_init_wrapper(); }
PyObject *pybind11_init_wrapper() {
{
const char *compiled_ver = "2" "." "7";
const char *runtime_ver = Py_GetVersion();
size_t len = std::strlen(compiled_ver);
if (std::strncmp(runtime_ver, compiled_ver, len) != 0 || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) {
PyErr_Format(PyExc_ImportError, "Python version mismatch: module was compiled for Python %s, " "but the interpreter version is incompatible: %s.", compiled_ver, runtime_ver);
return nullptr;
}
}
auto m = pybind11::module("example");
try {
pybind11_init_example(m);
return m.ptr();
} catch (pybind11::error_already_set &e) {
PyErr_SetString(PyExc_ImportError, e.what());
return nullptr;
} catch (const std::exception &e) {
PyErr_SetString(PyExc_ImportError, e.what());
return nullptr;
}
}
void pybind11_init_example(pybind11::module &m) {
m.doc() = "pybind11 example plugin";
m.def("add", &add, "A function which adds two numbers");
}
從展開的代碼第四行中可以看到,上面提到步驟中的第五步:給出一個特殊名字的函數已經體現了。在這個特殊函數中,調用了pybind11_init_wrapper
去創建了一個pybind11::module
的實例,並調用其def()
方,我們需要導出到Python的C++函數add
的地址作爲參數傳了進去,那我們順藤摸瓜,看看在def()
中執行了什麼操作。
// Wrapper for Python extension modules
class module : public object {
public:
PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
/// Create a new top-level Python module with the given name and docstring
explicit module(const char *name, const char *doc = nullptr) {
if (!options::show_user_defined_docstrings()) doc = nullptr;
#if PY_MAJOR_VERSION >= 3
PyModuleDef *def = new PyModuleDef();
std::memset(def, 0, sizeof(PyModuleDef));
def->m_name = name;
def->m_doc = doc;
def->m_size = -1;
Py_INCREF(def);
m_ptr = PyModule_Create(def);
#else
m_ptr = Py_InitModule3(name, nullptr, doc);
#endif
if (m_ptr == nullptr)
pybind11_fail("Internal error in module::module()");
inc_ref();
}
template <typename Func, typename... Extra>
module &def(const char *name_, Func &&f, const Extra& ... extra) {
cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
sibling(getattr(*this, name_, none())), extra...);
// NB: allow overwriting here because cpp_function sets up a chain with the intention of
// overwriting (and has already checked internally that it isn't overwriting non-functions).
add_object(name_, func, true /* overwrite */);
return *this;
}
PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
if (!overwrite && hasattr(*this, name))
pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
std::string(name) + "\"");
PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
}
};
有種豁然開朗的感覺。在def()
中,我們看到,我們傳遞進去的函數指針,被cpp_function
這個類封裝了起來,使用PyObject*
去保存,這樣方便對它進行引用計數的管理,因爲Python的垃圾回收主要依靠引用技術實現。之後它將這個cpp_function
作爲參數傳遞給了add_object()
函數。最終,在add_object()
中我們看到它調用了我們上面說到的第四步,調用PyModule_AddObject(m, name, PyObject*)
將函數添加到模塊。
那第二第三步在那裏?答案是構造函數裏面。在構造函數中,先創建了一個模塊對象,然後等待用戶調用的def()
的時候向方法表填充內容。
至此,pybind11的祕密在我面前展現的一覽無遺。
總結
本文從傳統方法入手,一步一步剖析pybind11如何化繁爲簡。有時候,基礎的東西雖然繁瑣,但是掌握了以後卻能方便我們理解其他更高層的內容。
References
[1] Extending Python with C or C++
本文首發於個人公衆號TensorBoy。如果你覺得內容還不錯,歡迎分享並關注我的公衆號TensorBoy,掃描下方二維碼獲取更多精彩原創內容!