gpt4 book ai didi

python - Cython:缓冲区类型不匹配,预期为 'int' 但得到了 'long'

转载 作者:太空狗 更新时间:2023-10-29 20:15:25 27 4
gpt4 key购买 nike

我无法将这个整数的内存 View 传递给这个(相当微不足道的)函数。 Python 给我这个错误:

ValueError: Buffer dtype mismatch, expected 'int' but got 'long'

有人可以帮助我了解发生了什么吗?查了一下stackoverflow,好像跟python是怎么解释类型的,C是怎么解释类型的。

%%cython
def myfunction(int [:] y):
pass

# Python code
import numpy as np
y = np.array([0, 0, 1, 1])
myfunction(y)

这会产生上面的 ValueError

编辑:这是我发现的其他一些事情。

澄清一下,如果我通过以下方式声明 y,此错误仍然存​​在:

y = np.array([0, 0, 1, 1], dtype='int')
y = np.array([0, 0, 1, 1], dtype=np.int)
y = np.array([0, 0, 1, 1], dtype=np.int64)

但是,如果我用

声明 y 它会起作用
y = np.array([0, 0, 1, 1], dtype=np.int32)

有没有人想提出建议,为什么会这样?投入 np.int32 会在不同的计算机上工作吗? (我使用的是 macbook pro retina,2013。)

最佳答案

您正在使用 Cython 的 int 类型,它只是 C int。我认为在 Mac(或大多数架构)上它是 int 32 位的。参见 wikiintelDoes the size of an int depend on the compiler and/or processor?

另一方面,long 表示 int64。 dtype='int'dtype=np.int 都等同于 np.int64

我认为您可能只是明确地将其定义为 numpy 类型之一:

cimport numpy as np
import numpy as np
cdef myfunction(np.ndarray[np.int64_t, ndim=1] y):
#do something
pass

这样读起来更清楚,后面不会有任何混淆。

编辑

较新的memoryviews语法是这样的:

cdef myfunction(double[:] y):
#do something with y
pass

关于python - Cython:缓冲区类型不匹配,预期为 'int' 但得到了 'long',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32262976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com