我需要在Python中为pyopencl创建类型为cl.cltypes.uint2
的变量。现在我以这种方式创建它:
key = np.array([(0x01020304, 0x05060708)], dtype=cl.cltypes.uint2)[0]
它肯定是肮脏的hack(如何以更干净的方式创建它?
此:key = cl.cltypes.uint2((0x01020304, 0x05060708))
由于错误而无法使用:'numpy.dtype' object is not callable
快速阅读您的链接表明它正在生成复合dtype。不用加载并运行它,我认为您的示例类似于
In [164]: dt = np.dtype([('x',np.uint16),('y',np.uint16)])
In [165]: np.array([(0x01020304, 0x05060708)], dtype=dt)
Out[165]: array([(772, 1800)], dtype=[('x', '<u2'), ('y', '<u2')])
In [166]: dt((0x01020304, 0x05060708))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-166-d71cce4777b9> in <module>
----> 1 dt((0x01020304, 0x05060708))
TypeError: 'numpy.dtype' object is not callable
并从数组中提取一条记录:
In [167]: np.array([(0x01020304, 0x05060708)], dtype=dt)[0]
Out[167]: (772, 1800)
In [168]: _.dtype
Out[168]: dtype([('x', '<u2'), ('y', '<u2')])
化合物dtype
永远不可调用。
我认为0d'标量'数组比用dtype函数创建的对象要好(尽管它们具有相似的方法)。
对于复合dtype:
In [228]: v = np.array((0x01020304, 0x05060708), dtype=dt)
In [229]: v
Out[229]: array((772, 1800), dtype=[('x', '<u2'), ('y', '<u2')])
In [230]: type(v)
Out[230]: numpy.ndarray
In [231]: v[()]
Out[231]: (772, 1800)
In [232]: type(_)
Out[232]: numpy.void
In [233]: _231.dtype
Out[233]: dtype([('x', '<u2'), ('y', '<u2')])
您可以将这样的数组强制转换为recarray
并获得record
对象,但我认为创建它们并不容易。
In [234]: v.view(np.recarray)
Out[234]:
rec.array((772, 1800),
dtype=[('x', '<u2'), ('y', '<u2')])
In [235]: _.x
Out[235]: array(772, dtype=uint16)
In [238]: v.view(np.recarray)[()]
Out[238]: (772, 1800)
In [239]: type(_)
Out[239]: numpy.record