【问题标题】:Default method arguments don't work默认方法参数不起作用
【发布时间】:2017-07-09 10:24:26
【问题描述】:

Cython 似乎没有认识到,sf::RenderTarget.clear() 方法可以使用不同的参数调用,并且只允许调用 .pxd 中最后声明的变体。

SFML 的头文件(source):

class RenderTarget {
    void clear(const Color& color = Color(0, 0, 0, 255));
}

我的 Cython .pxd:

cdef extern from 'SFML/Graphics.hpp' namespace 'sf' nogil:
    cppclass CRenderTarget 'sf::RenderTarget':
        void clear()
        void clear(const CColor&)

    cppclass CRenderWindow 'sf::RenderWindow' (CWindow, CRenderTarget):
        ...

我的 Cython 包装器:

cdef class RenderWindow(Window):
    cdef CWindow* c

    def __init__(self, ...):
        self.c = new CRenderWindow()
        ...

    def clear(self, Color color=None):
        if color is None:
            (<CRenderWindow*>self.c).clear()  # The error points here
        else:
            (<CRenderWindow*>self.c).clear(color.c[0])

编译错误:Call with wrong number of arguments (expected 1, got 0)

所以我只能调用.clear(color) 变体,而不是带有默认参数.clear() 的变体。我做错了什么?

我的实现尝试遵循 explained here,但我无法让它工作。

【问题讨论】:

  • 你为什么不尝试 .clear(None) 对于第一种情况?顺便说一句,渲染目标没有颜色变体的定义?而且我不明白如果你已经有一个默认参数以防颜色为无,为什么你必须创建两个函数。
  • Caliing .clear(None) 不幸的是无法编译。而且我没有创建两个函数,它们是在 SFML 的源代码中定义的,我正在尝试为它们制作一个包装器,以便能够从 Python 中调用它们。
  • 您列出 clear 函数的顺序是否重要(在您的 pxd 文件中)?
  • @DavidW 似乎只有 pxd 中定义的最后一个函数有效(对 Cython 可见)。
  • 非常相似的代码为我正确翻译(在 Cython 0.25.1 上)。检查您的 Cython 版本可能值得 - 如果它较低,则升级,如果它较高,则提交错误报告。

标签: python cython cythonize


【解决方案1】:

我为类似情况下的方法提供了别名 (C names)。在这种情况下

cdef extern from 'SFML/Graphics.hpp' namespace 'sf' nogil:
    cppclass CRenderTarget 'sf::RenderTarget':
        void clear0 "clear" ()

【讨论】:

  • 我认为你在这里弄错了 - void clear0 "clear"()?所以他们都指的是 C++ clear 但 Cython 认为他们有不同的名字。
  • 是的,我现在在我的代码中使用别名,正如你所建议的那样。我还发现了一个可能相关的错误报告:github.com/cython/cython/issues/1374
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 2015-03-09
  • 1970-01-01
相关资源
最近更新 更多