【问题标题】:memoryview and column-major / FORTRAN buffermemoryview 和 column-major / FORTRAN 缓冲区
【发布时间】:2019-02-26 15:15:13
【问题描述】:

我有一个用于列主数组的缓冲区(我通过cffi 将其作为字节获取)。

有没有办法通过 Python 的缓冲区协议的正确属性为其获取内存视图? cast 方法让我可以分配一个新的形状,但似乎没有让我指定视图是行主要还是列主要。

例如:

# Let b be my buffer of bytes for a column major array of integers
shape = (5, 2, 3)
mv = memoryview(b).cast('i', shape=shape)
# Expectedly not what I want as this is then assumed to be a
# C-style row-major array
mv.to_list()

【问题讨论】:

    标签: python python-3.x python-cffi


    【解决方案1】:

    要改变memoryview 的步幅/形状确实没有简单的方法而不深入到 C 中。最简单的方法是使用 NumPy(我在这里创建缓冲区,你应该跳过那行):

    shape = (5, 2, 3)
    b = bytearray('a' * np.dtype('i').itemsize * np.prod(shape))
    a = np.frombuffer(b, dtype='i').reshape(shape)
    a.strides = a.strides[::-1]
    m = memoryview(a)
    print(m.strides)
    

    【讨论】:

    • 谢谢。您提出的 numpy 解决方案似乎是唯一不需要编写 C 扩展来设置缓冲区属性的解决方案。我在 Python 错误跟踪器中打开了一个问题 - bugs.python.org/issue34778
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 2020-12-18
    • 2016-01-31
    相关资源
    最近更新 更多