如何在cython中将类型化的内存视图转换为NumPy数组?文档有
cimport numpy as np
import numpy as np
numpy_array = np.asarray(<np.int32_t[:10, :10]> my_pointer)
Run Code Online (Sandbox Code Playgroud)
我把它当作我的情况
np.asarray(<np.float_t[:, :]> my_memview)
Run Code Online (Sandbox Code Playgroud)
使用这个编译器告诉我:
Can only create cython.array from pointer or array
Run Code Online (Sandbox Code Playgroud)
复制与否并非如此具有决定性.我找不到任何帮助.
在接下来的回答"我可以强迫一个numpy ndarray获取其记忆的所有权吗?" 我尝试PyArray_ENABLEFLAGS通过Cython的NumPy包装器使用Python C API函数,发现它没有暴露.
以下尝试手动公开它(这只是重现故障的最小示例)
from libc.stdlib cimport malloc
import numpy as np
cimport numpy as np
np.import_array()
ctypedef np.int32_t DTYPE_t
cdef extern from "numpy/ndarraytypes.h":
void PyArray_ENABLEFLAGS(np.PyArrayObject *arr, int flags)
def test():
cdef int N = 1000
cdef DTYPE_t *data = <DTYPE_t *>malloc(N * sizeof(DTYPE_t))
cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &N, np.NPY_INT32, data)
PyArray_ENABLEFLAGS(arr, np.NPY_ARRAY_OWNDATA)
Run Code Online (Sandbox Code Playgroud)
失败并出现编译错误:
Error compiling Cython file:
------------------------------------------------------------
...
def test():
cdef int N = 1000
cdef DTYPE_t *data = <DTYPE_t *>malloc(N …Run Code Online (Sandbox Code Playgroud) 处理大型矩阵(NxM,1K <= N <= 20K&10K <= M <= 200K),我经常需要通过Cython将Numpy矩阵传递给C++来完成工作,这可以按预期工作而无需复制.
但是,有时我需要在C++中启动和预处理矩阵并将其传递给Numpy(Python 3.6).让我们假设矩阵是线性化的(因此大小为N*M,它是一维矩阵 - col/row major在这里无关紧要).根据这里的信息:在没有数据副本的情况下在Python中公开C计算数组并修改它以实现C++兼容性,我能够传递C++数组.
问题是如果我想使用标准向量而不是启动数组,我会得到分段错误.例如,考虑以下文件:
fast.h
#include <iostream>
#include <vector>
using std::cout; using std::endl; using std::vector;
int* doit(int length);
Run Code Online (Sandbox Code Playgroud)
fast.cpp
#include "fast.h"
int* doit(int length) {
// Something really heavy
cout << "C++: doing it fast " << endl;
vector<int> WhyNot;
// Heavy stuff - like reading a big file and preprocessing it
for(int i=0; i<length; ++i)
WhyNot.push_back(i); // heavy stuff
cout << "C++: …Run Code Online (Sandbox Code Playgroud)