栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

强制NumPy ndarray取得其在Cython中的内存所有权

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

强制NumPy ndarray取得其在Cython中的内存所有权

接口定义中只有一些小错误。以下为我工作:

from libc.stdlib cimport mallocimport numpy as npcimport numpy as npnp.import_array()ctypedef np.int32_t DTYPE_tcdef extern from "numpy/arrayobject.h":    void PyArray_ENABLEFLAGS(np.ndarray arr, int flags)cdef data_to_numpy_array_with_spec(void * ptr, np.npy_intp N, int t):    cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &N, t, ptr)    PyArray_ENABLEFLAGS(arr, np.NPY_OWNDATA)    return arrdef test():    N = 1000    cdef DTYPE_t *data = <DTYPE_t *>malloc(N * sizeof(DTYPE_t))    arr = data_to_numpy_array_with_spec(data, N, np.NPY_INT32)    return arr

这是我的

setup.py
文件:

from distutils.core import setup, Extensionfrom Cython.Distutils import build_extext_modules = [Extension("_owndata", ["owndata.pyx"])]setup(cmdclass={'build_ext': build_ext}, ext_modules=ext_modules)

用构建

python setup.py build_ext --inplace
。然后验证数据是实际拥有的:

import _owndataarr = _owndata.test()print arr.flags

除其他外,您应该看到

OWNdata: True

而且 ,这绝对是处理这个正确的方式,因为

numpy.pxd
究竟到所有其他功能导出到用Cython同样的事情。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/634323.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号