python - Cython:如何使用用户定义的 C++ 类转换?

标签 python c++ cython

Cython 的 documentation似乎对如何user-defined conversion保持沉默可以包裹。

例如,当以下 c++ 代码打印 1(即 truehere live)时:

#include <iostream>

struct X{
    operator bool() const{ return true;}    
};

int main() {
    X x;
    std::cout << x << "\n";
}

它在 Cython 中的“等价物”:

%%cython  -+
cdef extern from *:
    """
    struct X {
        //implicit conversion
        operator bool() const { return true; }
    };
    """
    cdef cppclass X:
        operator bool()  # ERROR HERE

def testit():
    cdef X x;
    print(x) # implicit cast, "should" print True

没有通过以下错误消息(在标有 ERROR HERE 的行中)进行 cythonized:

'operator' is not a type identifier

如何从 Cython 使用用户定义的转换,如果不能,有什么解决方法?

最佳答案

仅查看 bool 情况:

  1. 我不相信 print(x) 应该将它转换为 bool。 print(x) 查找到 Python 对象的转换(好吧,bool 可以转换为 Python 对象,但有点间接)。 Python 本身仅在相当有限的情况下使用 __bool__(Python 2 中的 __nonzero__),例如在 if 语句中,Cython 通常遵循 Python 行为作为一项规则。因此我将测试代码更改为

    def testit():
        cdef X x
        if x:
            print("is True")
        else:
            print("if False")
    
  2. operator bool() 给出错误

    'operator' is not a type identifier

    我假设它需要像所有其他 C++ 函数一样以返回类型开始(即 operator 没有特殊情况)。这有效(有点......见下一点......):

    bool operator bool()
    

    这个语法就是tested for in Cython's testsuite .

  3. 但是,您确实需要在文件顶部执行 from libcpp cimport bool 以获得 C++ bool 类型。

    <

如果您查看 if x: 的转换源,它最终会变成

__pyx_t_1 = __pyx_v_x.operator bool();
if (__pyx_t_1) {

operator bool 被显式调用(这在 Cython 中很常见),但在正确的位置使用,因此 Cython 清楚地理解它的用途。类似地,如果你执行 if x: 而没有定义运算符,你会得到错误

Object of type 'X' has no attribute 'operator bool'

再次表明这是 Cython 的一个特性。

这里显然存在一些文档错误,如果将来语法更改为更接近 C++,我不会 100% 感到惊讶。


对于更一般的情况:it looks like bool is the only type-conversion operator supported目前,您无法定义其他运算符。

关于python - Cython:如何使用用户定义的 C++ 类转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537827/

相关文章:

python - python 程序的 emacs 语法高亮问题

c++ - SSE 类型的容器

c++ - BGL 中顶点迭代器的度数

c++ - 二叉搜索树赋值运算符

python - Cython 中的高效算术特殊方法

logging - Cython 日志记录文件名和模块

python - 在 Python 中查找列表的 n 长度连续子列表的最优雅方法是什么?

python - 如何在 QtCharts 中添加子图?

python - 使用librosa了解STFT

python - 使用 setup.py Cythonize 但不编译 .pyx 文件