努比的__array_interface__不回字典

Numpy's __array_interface__ not returning dict

本文关键字:字典 interface array      更新时间:2023-10-16

我正在使用一个外部程序来计算一个用C++编写的矩阵,该矩阵通过boost::python与python接口。我想把这个C数组传递给numpy,根据作者的说法,这个能力已经用numpy的obj.__array_interface__实现了。如果我在python脚本中调用它,并将C++对象分配给X,我将获得以下内容:

print X
#<sprint.Matrix object at 0x107c5c320>
print X.__array_interface__
#<bound method Matrix.__array_interface__ of <sprint.Matrix object at 0x107c5c320>>
print X.__array_interface__()
#{'shape': (5, 5), 'data': (4416696960, True), 'typestr': '<f8'}
print np.array(X)
#Traceback (most recent call last):
#  File "<string>", line 96, in <module>
#ValueError: Invalid __array_interface__ value, must be a dict

根据我有限的理解,我认为问题是X.__array_interface__在没有()的情况下实际上不会返回任何内容。有没有办法将这些参数显式传递给np.array,或者解决这个问题的方法。

我对混合C++和python真的很陌生,如果这毫无意义,或者如果我需要阐述任何部分,请告诉我!

__array_interface__应该是一个属性(实例变量),而不是一个方法。因此,在C++中,或者在任何定义了"sprint.Matrix"对象的地方,更改它,使其不具有:

print X.__array_interface__
#<bound method Matrix.__array_interface__ of <sprint.Matrix object at 0x107c5c320>>

你有

print X.__array_interface__
#{'shape': (5, 5), 'data': (4416696960, True), 'typestr': '<f8'}

另一种选择是定义一个自定义包装类:

class SprintMatrixWrapper(object):
    def __init__(self, sprint_matrix):
        self.__array_interface__ = sprint_matrix.__array_interface__()

然后简单地做:

numpy.array(SprintMatrixWrapper(X))