cython:使用numpy.ctypeslib.ndpointer将浮点数组转换为python数组
我想在cython/python代码中使用c数组中的数据 为此,我尝试使用cython:使用numpy.ctypeslib.ndpointer将浮点数组转换为python数组,python,c,arrays,numpy,cython,Python,C,Arrays,Numpy,Cython,我想在cython/python代码中使用c数组中的数据 为此,我尝试使用numpy.ctypeslib.ndpointer转换c数组 我得到错误无法将'float*'转换为Python对象 下面是一个简单的例子,我试着开始运行了几天 假设我们有一个创建数组的c函数c_代码.c float *compute(int size) { float* array; array = malloc(sizeof(float)*size); int i; for (i=0;
numpy.ctypeslib.ndpointer
转换c数组我得到错误
无法将'float*'转换为Python对象
下面是一个简单的例子,我试着开始运行了几天
假设我们有一个创建数组的c函数<代码>c_代码.c
float *compute(int size)
{
float* array;
array = malloc(sizeof(float)*size);
int i;
for (i=0; i<size; i++)
{
array[i] = i;
}
return array;
}
setup.py
:
import numpy
from Cython.Distutils import build_ext
def configuration(parent_package='', top_path=None):
""" Function used to build our configuration.
"""
from numpy.distutils.misc_util import Configuration
# The configuration object that hold information on all the files
# to be built.
config = Configuration('', parent_package, top_path)
config.add_extension('cython_wrapper',
sources=['cython_wrapper.pyx'],
# libraries=['m'],
depends=['c_code.c'],
include_dirs=[numpy.get_include()])
return config
if __name__ == '__main__':
# Retrieve the parameters of our local configuration
params = configuration(top_path='').todict()
# Override the C-extension building so that it knows about '.pyx'
# Cython files
params['cmdclass'] = dict(build_ext=build_ext)
# Call the actual building/packaging function (see distutils docs)
from numpy.distutils.core import setup
setup(**params)
@DavidW指出,
numpy.ctypeslib.ndpointer
不是我想要做的事情的正确方法
基本上,我只想将c-array
转换为cython/python数组
在这个链接的帮助下,我找到了答案:
def py_compute(int size):
返回(计算(大小))
我正在用c释放内存,这样我就不必担心用python释放内存,因此可以使用这个非常简单的解决方案。虽然你的问题不是重复的,但我认为答案会是你想要的。我认为c类型不是正确的方法(在任何情况下,您都误解了用于声明函数接口的ndpointer)。您也可以寻找解决同一问题的不同方法,但是如果您想要一个numpy数组,您可能会发现第一个链接更有用。如果这是您的主要需求,我认为cython数组/memoryview方法(在我的第三条评论中)可能是最简单的选择。好。2件事:1)回答自己的问题比将答案编辑到问题中更有用。2)思考如何释放内存?我不认为它在你那里有非常简单的版本。。。
import numpy
from Cython.Distutils import build_ext
def configuration(parent_package='', top_path=None):
""" Function used to build our configuration.
"""
from numpy.distutils.misc_util import Configuration
# The configuration object that hold information on all the files
# to be built.
config = Configuration('', parent_package, top_path)
config.add_extension('cython_wrapper',
sources=['cython_wrapper.pyx'],
# libraries=['m'],
depends=['c_code.c'],
include_dirs=[numpy.get_include()])
return config
if __name__ == '__main__':
# Retrieve the parameters of our local configuration
params = configuration(top_path='').todict()
# Override the C-extension building so that it knows about '.pyx'
# Cython files
params['cmdclass'] = dict(build_ext=build_ext)
# Call the actual building/packaging function (see distutils docs)
from numpy.distutils.core import setup
setup(**params)
def py_compute(int size):
return <float[:size]> (compute(size))