【问题标题】:numpy and ctypes: dealing with viewsnumpy 和 ctypes:处理视图
【发布时间】:2016-12-19 00:14:46
【问题描述】:

我使用 ctypes 在 C 和 Python+numpy 之间进行互操作。两边的代码都是我写的。通常它会按预期工作,但我遇到了一个我不明白的奇怪错误。

我的问题是:发生了什么事?

我正在使用 gcc 6.2.1 开发 Linux (Manjaro 16.10)。 python 2.7.12 和 numpy 1.11.2。


我的 C 代码的简化版本:

void imp(double *M) {/*do stuff, assumes M is a 3x3 row-major matrix*/}

我的 Python 代码的简化版本:

lib = ctypes.CDLL('path/to/lib.so')

def function(M):
    assert(M.dtype == np.float64)
    lib.imp(M.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))

# Snippet 1: Doesn't work correctly, gives nonsense results.
print my_var.dtype  # prints 'float64'
print my_var.shape  # prints '(3, 3)'
function(my_var)    # the assert in function doesn't fail

# Snippet 2: Works correctly, gives the expected results.
my_var = my_var.astype(np.float64) # (!!)
print my_var.dtype  # The same...
print my_var.shape  # ...as in...
function(my_var)    # ...snippet 1

更新

替换

my_var = my_var.astype(np.float64)

my_var = my_var.copy()

同样有效。显然,问题的根源在于 my_var 是一个 numpy 的视图(我已经通过打印 my_var.base 进行了检查)。

所以我修改后的问题是:如果这些数组实际上可能是视图,那么使用 ctype 传递 numpy 数组的正确方法是什么?在调用 c 函数之前复制所有参数是否不可避免?

【问题讨论】:

    标签: python c numpy ctypes


    【解决方案1】:

    查看numpy.ascontiguousarray 和相关的numpy.as* 函数。如有必要,这些将复制一份,以便将您的数据转换为适合您的函数的良好形式,但如果数组都正常,那么它们将被单独保留。

    有用的参考资料:

    【讨论】:

      猜你喜欢
      • 2013-09-29
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多