Cython将扩展模块传递给python会导致to_py_call_code错误

时间:2017-03-02 02:44:36

标签: python c++ cython

我刚刚开始熟悉Cython,试图将一些类从C ++库包装到Python方法和类中。我真正不了解的是如何将这些扩展模块传递到python世界。

以下是我的pyx文件中的代码片段,它试图公开c ++类和方法:

# distutils: language = c++
# distutils: sources = Demuxer.cpp, SharedUtil.cpp, ffmpeg_tpl.c, tpl.c
# distutils: libraries = spam eggs
# distutils: include_dirs = /opt/food/include

from cython.operator cimport dereference as deref

cdef extern from "Demuxer.h":
    cdef cppclass DemuxPkt:
        int streamID
        int tb_num
        int tb_den
        bint splitPoint     
        int ts
        int duration 
        unsigned char* data
        DemuxPkt()
    int initDemuxWithFileImpl(char*)
    int getNextChunkImpl(DemuxPkt*)

以下是试图将它们包装到python世界中的代码片段

cdef class Demuxer:

    def __cinit__(self, fname, stream=None, length=None):
        #if stream is not None and length is not None:
         #   initDemuxWithFileImpl(stream, length)
        #else:
        initDemuxWithFileImpl(fname)

    cpdef getNextChunk(self):
        cdef DemuxPacket _dpkt = DemuxPacket()
        getNextChunkImpl(_dpkt._thisptr) # Is this correct??
        return _dpkt


cdef class DemuxPacket(object):

    """A packet of encoded data 
    """
    cdef DemuxPkt* _thisptr
    def __cinit__(self, flag):
        #if flag is _cinit_bypass_sentinel:
        #    return
        self._thisptr = new DemuxPkt()
        if self._thisptr == NULL:
            raise MemoryError()

    def __dealloc__(self):
        if self._thisptr != NULL:
            del self._thisptr

    def __call__(self):
        return deref(self._thisptr)()

    cpdef long getMillisecondsTs(self):
        return (self._thisptr.ts*self._thisptr.tb_num)/(self._thisptr.tb_den/1000)

    cpdef long getMillisecondsDuration(self):
        return (self._thisptr.duration*self.struct.tb_num)/(self._thisptr.tb_den/1000)

但是,当我运行cython时,会出现以下错误:

AttributeError: 'ErrorType' object has no attribute 'to_py_call_code'

我不知道这条消息,也不知道如何前进。我在Ubuntu 14.0.4上使用的Cython版本是0.25.2。

任何建议都表示赞赏!!

提前致谢!!

1 个答案:

答案 0 :(得分:0)

问题出在__call__。您尝试使用DemuxPkt::operator(),但您还没有告诉Cython它。将其添加到cppclass定义:

cdef extern from "Demuxer.h":
    cdef cppclass DemuxPkt:
        # .. everything else unchanged
        int operator()()

我猜测返回类型为int。显然这可能不是真的,所以改变它以匹配真实的返回类型。