使内存视图 C-连续 Fortran-连续
Making a memoryview C-contiguous Fortran-contiguous
我在 Python 代码中使用 C 连续内存视图,我想使用需要 Fortran 连续内存视图的 dgemm
。
我想使用函数 PyMemoryView_GetContiguous found here 但我不知道如何访问它。
有人知道我必须执行哪个导入吗?
我不想使用 copy_fortran() 函数,因为它确实会降低我的代码速度。
不幸的是,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
不会 return 可写内存视图,除非它不需要制作副本,并且 Cython 要求分配给类型化内存视图的东西是可写的,所以你只能将其用作 Python 对象。
虽然您可以获得指向第一个元素的指针 - 创建的基础对象是 bytes
/str
对象,因此您可以获得 char*
然后将其转换为你需要的任何指针。这应该足以调用您的 Fortran 函数:
cdef char* as_bytes = f_contig.obj
some_function(<double*>as_bytes)
我在 Python 代码中使用 C 连续内存视图,我想使用需要 Fortran 连续内存视图的 dgemm
。
我想使用函数 PyMemoryView_GetContiguous found here 但我不知道如何访问它。
有人知道我必须执行哪个导入吗?
我不想使用 copy_fortran() 函数,因为它确实会降低我的代码速度。
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
不会 return 可写内存视图,除非它不需要制作副本,并且 Cython 要求分配给类型化内存视图的东西是可写的,所以你只能将其用作 Python 对象。
虽然您可以获得指向第一个元素的指针 - 创建的基础对象是 bytes
/str
对象,因此您可以获得 char*
然后将其转换为你需要的任何指针。这应该足以调用您的 Fortran 函数:
cdef char* as_bytes = f_contig.obj
some_function(<double*>as_bytes)