python - numpy 和 ctypes : dealing with views

标签 python c numpy ctypes

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

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

我正在 Linux (Manjaro 16.10) 上工作,使用 gcc 6.2.1。 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 的 View (我已经通过打印 my_var.base 检查了这一点)。

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

最佳答案

查看 numpy.ascontigouslyarray 和相关的 numpy.as* 函数。如果有必要的话,它们将制作一个副本,以便将数据转换为适合函数的良好形式,但如果数组都很好,那么它们将被保留。

有用的引用:

关于python - numpy 和 ctypes : dealing with views,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41214268/

相关文章:

python - 将悬停工具提示添加到 Bokeh 直方图

使用 C 在 Raspberry Pi 上设置时钟 gettime

c - 为什么人们不使用异或交换?

c++ - 在 C 中递增一个 volatile 变量

python - 如何让 np.save 为 ndarray 子类工作?

python - 简洁的Python方法来改变一个值,如果它不是Falsey

python - SSHTunnelForwarder- "IP is not a string (NoneType)"

python - Matplotlib imshow - 显示不同的颜色

python - 在 appengine 上使用 webapp2 创建用户配置文件

python - 设置tensorflow conv2d操作的权重和偏差张量