Cython中是否可以使用C++风格的内部typedef?

2024-10-01 17:28:21 发布

您现在位置:Python中文网/ 问答频道 /正文

C++中,可以声明类或结构成员的类型别名:

struct Foo
{
    // internal type alias
    typedef int DataType;

    // ...
};

在Cython有什么方法可以做同样的事情吗?我尝试过最明显的方法:

^{pr2}$

但这行不通:

Error compiling Cython file:
------------------------------------------------------------
...
# distutils: language=c++

cdef struct Foo:
    ctypedef int DataType
   ^
------------------------------------------------------------

internal_typedefs_example.pyx:4:4: Expected an identifier, found 'ctypedef'

这仅仅是Cython的一个基本限制(我使用的是v0.21.2),还是有变通方法?在


为什么要使用内部typedef?有几个一般原因-this previous SO question涵盖了其中一些原因。在

我感兴趣的特定案例是包装一组模板C++类,看起来类似于:

struct Foodataset
{
    typedef int DataType;
    typedef float ReturnType;

    // methods, other important stuff
};

struct BarDataset
{
    typedef long DataType;
    typedef double ReturnType;

    // methods, other important stuff
};

template <class Dataset>
class DataProcessor{

    DataProcessor(Dataset& input_data);

    typedef typename Dataset::DataType T;
    typedef typename Dataset::ReturnType R;

    T getDataItem();
    R computeSomething(); /* etc. */

    // do some other stuff that might involve T and/or R
};

将typedef放在结构内部可以提供更好的封装,因为我只需要传递一个模板参数(即Dataset类),而不是单独指定特定于Dataset类型的T, R, ...。在

我意识到要找到解决这个问题的方法并不太困难——我最感兴趣的是得到一个明确的答案,即Cython目前是否可以使用内部typedef。在


Tags: 方法类型foo结构datasetstructcythonint
2条回答
< C++ >^{} is a keyword to declare a class。因此,内部typedef可以在Cython中声明为:

cdef cppclass Foo:
    ctypedef int DataType

据我所知,Cython目前不支持这一功能。但是你不能在结构之外定义它吗?在

Cython目前不被设计为C++的替代品,而是一种加速Python代码热点的方法。如果你需要更多的参与,只需在C++中编写并公开Python绑定。在

相关问题 更多 >

    热门问题