1

好的,我认为手册建议使用 Cython 的 C++ 支持后出现一个奇怪的错误(用于__cinit__分配堆 RAM 并__dealloc__再次释放它。

我有一个 C++ 类,callocmalloc的构造函数中有一些 RAM,free而析构函数中有一些 RAM。如有必要,我会发布这个,但错误不是来自 C++ 领域,newanddelete调用工作正常,所以我现在只给你 cython:

cdef extern from "../clibs/adjacency.hpp":

  cdef cppclass Adjacency:
    int* _bv
    void** _meta
    unsigned int length
    Adjacency(int graph_order, int meta_on)
    int get(int i, int j)
    void set(int i, int j, int on, void* meta)
    void reset_to_zero()
    void edges_iter(void* global_meta, void (*callback)(void*, int, int, void*))

cdef class Graph:
  cdef Adjacency* adj

  def __init__(self, graph_order):
    print "__init__"

  def __cinit__(self, graph_order, *args, **kwargs):
    print "__cinit__"
    print "allocating, no meta."
    self.adj = new Adjacency(<int>graph_order, 0)

  def __dealloc__(self):
    print "__dealloc__"
    del self.adj

当我对此进行测试时,我得到以下信息:

In [1]: import graph

In [2]: g = graph.Graph(302)
__cinit__
allocating, no meta.
__init__

In [3]: ^D
Do you really want to exit ([y]/n)? 
__dealloc__
Python(7389,0x7fff70f9acc0) malloc: *** error for object 0x100defa08: incorrect
checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap

我有时也会得到段错误而不是不正确的校验和。

我破解了 cython 生成的 C++ 文件,并在delete调用周围添加了以下内容:

/* "graph.pyx":75
 *   def __dealloc__(self):
 *     print "__dealloc__"
 *     del self.adj             # <<<<<<<<<<<<<<
 * 
 *   def __init__(self, graph_order):
 */
printf("about to delete adj:\n");
delete __pyx_v_self->adj;
printf("just deleted adj!\n");

我们可以清楚地看到我拨打的电话delete运行良好:

In [1]: import graph

In [2]: g = graph.Graph(302)
__cinit__
allocating, no meta.
__init__

In [3]: ^D
Do you really want to exit ([y]/n)? 
__dealloc__
about to delete adj:
just deleted adj!
Python(7389,0x7fff70f9acc0) malloc: *** error for object 0x100defa08: incorrect
checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap

在我按照 Cython 手册中的指示完成整理,Python 会发脾气。

我也只是尝试设置self.adj = NULLin __dealloc__,以防 Python 试图查看我的对象内部,但这没有帮助。

任何想法我做错了什么?

4

1 回答 1

0

我在我的 C++ 代码中犯了一个错误(我没有显示)。

我有一堆这样的功能:

if (_meta != NULL) {
  // do stuff with _meta, like loop over the void*s
}

但是在构造函数中,我在设置之前调用了其中一个_meta = NULL;......

于 2013-01-02T11:36:14.050 回答