python - 防止许多独立的Python对象之一递减为0并破坏其他Python对象所依赖的C指针

标签 python python-3.x python-c-api

我正在使用一个用 Python C 扩展封装的旧 C 库。 C 库有一个递归数据结构 Foo,其 API 类似于以下内容:

Foo *Foo_create(void)  /* Create new Foo memory */

int Foo_push(Foo *parent, int field, Foo *child)  /* Add a child Foo to a parent Foo */

int Foo_destroy(Foo *foo) /* Framework will free all children, caller cannot reuse children after */

Foo *Foo_pop(Foo *parent, int field) /* User responsible for calling Foo_destroy on popped field */

我有一个包装 FooPyFoo 结构,类似于:

typedef struct {
    PyObject_HEAD
    Foo *foo;
    PyObject *parent;
} PyFoo;

以及适当包装 Foo_* 函数和 incref/decref 的其他函数。

我遇到的问题是两个具有独立引用计数的独立 PyFoo 对象可能指向同一个 Foo *。如果其中一个 PyFoo 对象超出范围,它将调用 Foo_destroy,但用户可能会访问第二个 PyFoo 对象并导致段错误。

我试图阻止我的库的用户在 Python 中执行以下操作:

parent = Foo()     # Foo_create();  parent's refcount is 1
a = Foo()          # Foo_create();  a's refcount is 1
parent[1] = a      # Foo_push(parent, 1, a); parent's refcount is 2; a's refcount is 1

b = parent.pop(1)  # Foo_pop(parent, 1); 
# parent's refcount is 1; a's refcount is 1; b's refcount is 1
# a and b's are now independent PyFoo objects with reference count = 1
# HOWEVER both of the *foo pointers point to the same memory

# Delete a, dropping reference count to 0, which calls Foo_destroy
del a              # parents refcount is 1; a's refcount is 0; b's refcount is 1

# Access b, which may segfault, since Foo_destroy was called in the last call.
print(b)

换句话说,ab都指向同一个Foo内存。然而,它们是独立的 Python 对象,具有独立的引用计数。一旦a超出范围,它将破坏b指向的内存。访问 b 可能会出现段错误。

这似乎是编写 Python 扩展时的常见问题。

我想我想要的是某种基于 Foo 指针的引用计数的方法。例如,在上面的示例中,ab 实际上应该具有相同的标识。或者也许我需要的是一些数据结构来计算共享相同 Foo 指针的 PyFoo 的数量,并且仅当 Foo 指针的计数降至 0 时才调用 Foo_destroy 。

解决这个问题的惯用方法是什么?


这里是C中对应的场景:

Foo *parent = Foo_create();
Foo *a = Foo_create();
Foo_push(parent, 1, a);
Foo *b = Foo_pop(parent, 1);
/* a and b both point to same memory */
Foo_destroy(a);
/* better not access b after this */
a = NULL;
b = NULL;

最佳答案

不确定“惯用方式”,但在 cppyy ( http://cppyy.org ) 中,我跟踪 python 对象(按类型)以保留身份,而 pybind11 ( https://pybind11.readthedocs.io ) 做了类似的事情,所以这是一个可行的想法。

C++ 的唯一问题是多重(虚拟)继承,因此不必担心您的情况,因此只是为了完整性,其中父类和派生类之间的偏移量不为零,因此需要自动转换来确保当指向派生实例的指针作为指向基类的指针返回时,偏移量不会扰乱跟踪。

要实现,请保留指向 Python 对象的 C 指针的 HashMap 。当将 Foo* 返回到 Python-land 时,检查它是否已存在于映射中,并根据需要重新使用。当引用计数达到 0 时,也从 map 中删除该对象。请注意,您不需要增加引用计数或保留弱引用,因为 HashMap 永远不会离开 C-land。

此外,如果您可以控制 C-land 中的 Foo 销毁,那么我建议使用回调将 Python 代理的 Foo* 设置为 NULL 并检查所有访问函数中的 NULL(如果 C++ 提供回调,cppyy 也会执行类似的操作)。

编辑:在此处添加代码链接,否则我会用完字符。

首先:这是 C++,所以我的生活稍微轻松一点,因为我可以使用 STL 容器,而不必将指针强制转换为整数,但是,是的,如果您这样做,那是完全安全的。

出于性能原因,我收集每种类型的引用(使映射更小),请参阅此处的 fCppObjects: https://bitbucket.org/wlav/cpycppyy/raw/c6e7662bab1623e6cb15ddf59e94423a6081d66f/src/CPPScope.h

当返回一个携带 C++ 指针的新代理时,该对象通过 MemoryRegulator 注册,当对象消失时,它会被取消注册: https://bitbucket.org/wlav/cpycppyy/raw/c6e7662bab1623e6cb15ddf59e94423a6081d66f/src/MemoryRegulator.h https://bitbucket.org/wlav/cpycppyy/raw/c6e7662bab1623e6cb15ddf59e94423a6081d66f/src/MemoryRegulator.cxx

Hook 用于框架接管行为,例如一个客户端代码更喜欢将所有指针存储在单个映射中。

使用标志是出于一些极端情况的性能原因。

查找/注册发生在对象中的各个位置,因为对象可能由于各种原因(构造、函数返回、变量访问)而跨越边界。函数返回在这里: https://bitbucket.org/wlav/cpycppyy/raw/c6e7662bab1623e6cb15ddf59e94423a6081d66f/src/ProxyWrappers.cxx

BindCppObjectNoCast中查找调用。

销毁发生在对象消失时,请参阅代理类: https://bitbucket.org/wlav/cpycppyy/raw/c6e7662bab1623e6cb15ddf59e94423a6081d66f/src/CPPInstance.cxx 特别是 op_dealloc_nofree(删除 C++ 端的帮助程序,而不是 Python),它是从普通 tp_dealloc 调用的。

对于 pybind11,这些函数称为 register_instancederegister_instance,您可以在此处找到它们: https://raw.githubusercontent.com/pybind/pybind11/master/include/pybind11/detail/class.h

注册发生在名为 registered_instances 的单个多重映射中,可在此处找到: https://raw.githubusercontent.com/pybind/pybind11/master/include/pybind11/detail/internals.h

查找位于此处的 get_object_handle 中: https://raw.githubusercontent.com/pybind/pybind11/master/include/pybind11/cast.h 它执行 ptr 和类型的匹配。

即。与 cppyy 几乎相同(只是效率较低)。

关于python - 防止许多独立的Python对象之一递减为0并破坏其他Python对象所依赖的C指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59686499/

相关文章:

python - 如何分组并一次加入多列的多行?

python - 将字符串从 C 传递到 Python 进行多处理,无需进行额外的复制

python - Tkinter 如何绑定(bind)到 shift+tab

python 如何检索文件标志

python - 在 python3 中未检测到模块,但在 python2 中工作

python - 将 Python 长整数转换为 C 字符数组

python - 如何将 const char* 从 python 传递给 c 函数

python - 如何根据另一个包含通配符的列表过滤列表?

python - 拆分字符串,忽略引号内的定界符(python)

python-3.x - 在作业 Circle Ci 中使用 Blackbox 时出现错误 "gpg: decryption failed: No secret key"