【问题标题】:Seg fault when passing python object into class wrapped with Cython将 python 对象传递到用 Cython 包装的类时出现段错误
【发布时间】:2015-03-12 16:48:44
【问题描述】:

我使用 Cython 包装了许多 C++ 类,它们设法编译。但是,当我尝试使用 python 级别的模块时,我遇到了分段错误(11),所以我想知道我包装的内容是正确的。 “Foo.h”中的A是一个抽象类。

source.pyx

cdef extern from "Foo.h":
   cdef cppclass A:
      A(MPI_comm comm, int x)
cdef extern from "Foo1.h":
   cdef cppclass B:
      B(A* obj, int y)

cdef class pyA:
   cdef A *thisptrA
   def __cinit__(self,MPI.Comm _comm, int x):
      pass
   def __dealloc__(self):
      pass
cdef class pyB:
   cdef B* thisptrB
   cdef pyA obj
   def __cinit__(self, pyA obj, int y):
      self.thisptrB = new B(obj.thisptrA, y) 
   def __dealloc__(self):
      del self.thisptrB

testscript.py

import pyA, pyB
class C(pyA):
   def __init__(self, comm, x):
      self.x = x

comm = MPI.COMM_WORLD
x = 2
y = 24
Aobj = C(comm, x)

Bobj = pyB(Aobj, y)

似乎每当我尝试初始化pyB时,语句都会出现分段错误

self.thisptrB = newB(obj.thisptrA, y)

有人知道我哪里出错了吗?

【问题讨论】:

    标签: python c++ cython


    【解决方案1】:

    您永远不会在pyA 中分配thisptrA。因此它指向的东西要么是空的,要么是随机的(我不确定 Cython 是哪个)。

    导致分段错误的确切原因可能隐藏在B 的构造函数中,您不要短我们。

    您可能需要考虑的另一件事是:您可能希望确保A 的生命周期超过(我假设)拥有指向它的指针的B 的生命周期。一种方法是在您的PyB 中保留对PyA 的引用(即在__init__ 中为PyB 放入self._held_A = obj

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 2021-11-12
      • 2017-04-03
      • 2021-01-16
      • 1970-01-01
      相关资源
      最近更新 更多