简体   繁体   English

需要帮助以了解Cython-查找示例但不起作用

[英]Need help for understanding Cython -find an example but doesn't working

I have a problem for understanding Cython and pxd. 我在理解Cython和pxd时遇到问题。 I have find this code on internet but doesn't working. 我在互联网上找到了此代码,但是无法正常工作。 Can you explain me why ? 你能解释一下为什么吗?

The error when I compile: 我编译时的错误:

warning: test.pyx:1:0: Overriding cdef method with def method. 警告:test.pyx:1:0:用def方法覆盖cdef方法。

test.pxd:6:14: C method 'foo' is declared but not defined test.pxd:6:14:C方法'foo'已声明但未定义

I find this example here : https://cython.readthedocs.io/en/latest/src/tutorial/pure.html 我在这里找到此示例: https : //cython.readthedocs.io/en/latest/src/tutorial/pure.html

I have do an error into the compilation ? 我在编译时出错了吗?

compile.py : compile.py:

import os
import sysconfig

from distutils.core import setup
from Cython.Build import cythonize

fichier = "test.pyx"

setup(
    ext_modules = cythonize(fichier)
)

test.pyx : test.pyx:

def myfunction(x, y=2):
    a = x - y
    return a + x * y

def _helper(a):
    return a + 1

class A:
    def __init__(self, b=0):
        self.a = 3
        self.b = b

    def foo(self, x):
        print(x + _helper(1.0))

test.pxd : test.pxd:

cpdef int myfunction(int x, int y=*)
cdef double _helper(double a)

cdef class A:
    cdef public int a, b
    cpdef foo(self, double x)

This is to do with the filename. 这与文件名有关。 .pyx files are dealt with as Cython files (ie they have to match the .pxd files). .pyx文件作为Cython文件处理(即,它们必须与.pxd文件匹配)。 However .py files are interpreted as "pure Python mode" (since they also have to work in Python). 但是, .py文件被解释为“纯Python模式”(因为它们也必须在Python中工作)。

If you rename your .pyx file to .py it will work. 如果将.pyx文件重命名为.py ,它将起作用。


This is stated pretty clearly in the documentation you linked to: 您链接到的文档中清楚地说明了这一点:

While declarations in a .pyx file must correspond exactly with those of a .pxd file with the same name (and any contradiction results in a compile time error, see pxd files), the untyped definitions in a .py file can be overridden and augmented with static types by the more specific ones present in a .pxd 虽然.pyx文件中的声明必须与具有相同名称的.pxd文件中的声明完全一致(并且任何矛盾都会导致编译时错误,请参阅pxd文件),但.py文件中的未类型化定义可以被覆盖和扩充带有静态类型的.pxd中存在更具体的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM