Skip to main content
 首页 » 编程设计

python之Cython 中的 "not a type identifier"错误

2025年01月19日13mfryf

我是 Cython 的新手,我正在尝试让一个测试项目工作,从 Python 调用 C 函数:

测试.cpp:

void testFn(int arr[]); 
 
void testFn(int arr[]) 
{ 
    arr[0] = 1; 
    arr[1] = 2; 
}  

caller.pyx:

cdef extern from "test.cpp": 
    void testFn(int arr[]) 
 
cpdef myTest(*arr): 
    testFn(arr) 

setup.caller.py:

from distutils.core import setup 
from distutils.extension import Extension 
from Cython.Distutils import build_ext 
 
sourcefiles = ['caller.pyx'] 
ext_modules = [Extension("caller", sourcefiles)] 
 
setup( 
    name = 'test app', 
    cmdclass = {'build_ext': build_ext}, 
    ext_modules = ext_modules 
) 

但是当我尝试构建项目时出现错误:

$ python setup.caller.py build_ext --inplace 
running build_ext 
cythoning caller.pyx to caller.c 
 
Error compiling Cython file: 
------------------------------------------------------------ 
... 
cdef extern from "test.cpp": 
    void testFn(int arr[]) 
 
cpdef myTest(*arr): 
     ^ 
------------------------------------------------------------ 
 
caller.pyx:4:6: 'myTest' is not a type identifier 

请您参考如下方法:

在我的例子中,第二个定义不需要“cpdef”或“cdef”,通常的“def”就可以了:

def myTest(int[:] arr): 
    testFn(&arr[0])