【发布时间】:2017-10-29 21:24:32
【问题描述】:
我正在尝试让一个测试项目工作,该项目通过 Python 调用一个带有数组参数的 C 函数:
test.cpp:
void testFn(int arr[]);
void testFn(int arr[])
{
arr[0] = 1;
arr[1] = 2;
}
caller.pyx:
import ctypes
cdef extern from "test.cpp":
void testFn(int arr[])
def myTest():
a = [0, 0]
arr = a.ctypes.data_as(ctypes.POINTER(ctypes.c_integer))
testFn(arr)
print(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:
------------------------------------------------------------
...
def myTest():
a = [0, 0]
arr = a.ctypes.data_as(ctypes.POINTER(ctypes.c_integer))
testFn(arr)
^
------------------------------------------------------------
caller.pyx:13:11: Cannot convert Python object to 'int *'
【问题讨论】:
-
你需要给
arr一个类型。cdef int* arr应该可以解决问题。