这是一天半的cross-post of a question I asked in the cython-user group,但还没有得到任何回复,所以我在一个更一般的论坛上试试运气
我一直在尝试用以下方法来包装以下代码,并且存在各种程度的错误。大量的搜索使我绊倒了类似的问题,也是一张出色的心愿单,但老实说,我不确定我是否走在正确的道路上。
plow_types.h:
namespace Plow {
struct JobState {
enum type {
INITIALIZE = 0,
RUNNING = 1,
FINISHED = 2
};
};
...
class JobFilterT {
public:
...
std::vector<JobState::type> states;
...
所以我试图包装这个Plow::JobState::type
枚举。在找到另一个类似的帖子后,我得到的最接近的结果就是这次尝试:
plow_types.pxd:
cdef extern from "rpc/plow_types.h" namespace "Plow":
enum JobState_type "Plow::JobState::type":
INITIALIZE "Plow::JobState::INITIALIZE"
RUNNING "Plow::JobState::RUNNING"
FINISHED "Plow::JobState::FINISHED"
struct JobState:
JobState_type type
...
cdef cppclass JobFilterT:
vector[JobState_type] states
我收到错误:
src/plow.cpp: In function ‘std::vector<Plow::JobState::type, std::allocator<Plow::JobState::type> > __pyx_convert_vector_from_py_enum__Plow_3a__3a_JobState_3a__3a_type(PyObject*)’:
src/plow.cpp:6688: error: invalid conversion from ‘long int’ to ‘Plow::JobState::type’
我试图在我的cython pyx中简单地定义自己的常量版本并将所有内容视为int(vector[int] states
),但编译器抱怨不知道如何从int long
进行转换到Plow::JobState::type
。
答案 0 :(得分:8)
在尝试了令人难以置信的数量组合之后,我终于想通了。在提出这个问题之前,我离最后一次尝试还不远......
<强> plow_types.pxd:强>
我需要忘记那个JobState
结构,并且只包装枚举。但我还需要将它们映射到cython中的新名称,以避免使用类似的命名空间技术与其他枚举进行名称冲突。
cdef extern from "rpc/plow_types.h" namespace "Plow":
ctypedef enum JobState_type "Plow::JobState::type":
JOBSTATE_INITIALIZE "Plow::JobState::INITIALIZE"
JOBSTATE_RUNNING "Plow::JobState::RUNNING"
JOBSTATE_FINISHED "Plow::JobState::FINISHED"
现在我可以在JobState_type
之类的内容中引用vector[JobState_type]
。然后我用这种方法以一种只读的方式在python中使我的常量可用:
<强> job.pyx:强>
cimport cython
@cython.internal
cdef class _JobState:
cdef:
readonly int INITIALIZE
readonly int RUNNING
readonly int FINISHED
def __cinit__(self):
self.INITIALIZE = JOBSTATE_INITIALIZE
self.RUNNING = JOBSTATE_RUNNING
self.FINISHED = JOBSTATE_FINISHED
JobState = _JobState()
这为我提供了JobState
的公共实例,具有只读常量属性。
当需要从python值列表转换回vector[JobState_type]
时,我会这样做:
someList = [JobState.RUNNING]
...
cdef:
JobState_type i
vector[JobState_type] vec_states
for i in someList:
vec_states.push_back(i)