Python 使内存视图C连续Fortran连续
我在Python代码中使用C-连续内存视图,我想使用需要Fortran连续内存视图的Python 使内存视图C连续Fortran连续,python,fortran,cython,contiguous,Python,Fortran,Cython,Contiguous,我在Python代码中使用C-连续内存视图,我想使用需要Fortran连续内存视图的dgemm。 我想使用找到的函数PyMemoryView\u getContinental,但我不知道如何访问它 有人知道我要做什么吗 我不想使用copy_fortran()函数,因为它确实会降低我的代码速度。PyMemoryView_getcontinuous看起来并没有作为Cython标准的一部分公开。但包装起来应该相当容易: from cpython.buffer cimport PyBUF_READ #
dgemm
。
我想使用找到的函数PyMemoryView\u getContinental,但我不知道如何访问它
有人知道我要做什么吗
我不想使用copy_fortran()函数,因为它确实会降低我的代码速度。
PyMemoryView_getcontinuous
看起来并没有作为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\u fortran
快得多
但是有一个问题-
PyMemoryView\u getcontinuous
不会返回可写的memoryview,除非它不必制作副本,Cython要求分配给类型化memoryview的内容是可写的,因此您只能将其用作Python对象
您可以获得指向第一个元素的指针-创建的底层对象是一个字节
/str
对象,因此您可以获得一个字符*
,然后将其转换为所需的任何指针。这应该足以调用Fortran函数:
cdef char* as_bytes = f_contig.obj
some_function(<double*>as_bytes)
cdef char*as_bytes=f_contig.obj
某些_函数(作为_字节)
A注释,因为这有点猜测:看起来您当前的矩阵是按行主顺序存储的,这是您认为需要的矩阵的转置。但是你能在dgemm中使用C(T)=(AB)(T)=B(T)A(T)和转置选项来避免改变内存布局吗?(其中(T)表示转置)这就是我最终解决问题的方法。谢谢