使一个内存视图C-contiguous Fortran-contiguous

时间:2017-07-17 11:43:05

标签: python fortran cython contiguous

我在Python代码中使用C-contiguous内存视图,我想使用需要Fortran连续内存视图的varchar。 我想使用函数 PyMemoryView_GetContiguous 找到here,但我不知道如何访问它。

有人知道我必须做哪些导入吗?

我不想使用函数copy_fortran(),因为它真的会减慢我的代码。

1 个答案:

答案 0 :(得分:0)

不幸的是,

PyMemoryView_GetContiguous看起来不像Cython标准的一部分那样被曝光。它应该相当容易包装:

from cpython.buffer cimport PyBUF_READ # we'll need this later

cdef extern from "Python.h":
    # copy the signature replacing PyObject* with object to let Cython
    # handle the reference counting
    object PyMemoryView_GetContiguous(object, int, char)

def test(double[:,::1] c_contig):
   f_contig = PyMemoryView_GetContiguous(c_contig, PyBuf_READ,'F')
   # .... do something useful

请注意,这仍然会涉及复制所有内存(这绝对是不可避免的!)所以不太可能明显快于copy_fortran

虽然存在问题 - PyMemoryView_GetContiguous不会返回可写的内存视图,除非它不需要复制,并且Cython要求分配给类型化内存视图的内容是可写的,所以你可以仅将其用作Python对象。

您可以获得指向第一个元素的指针 - 创建的基础对象是bytes / str对象,因此您可以获得char*然后将其转换为任何指针你需要。这应该足以调用您的Fortran函数:

cdef char* as_bytes = f_contig.obj
some_function(<double*>as_bytes)