Numpy的__array_interface__没有返回dict

Dan*_*iel 6 c++ python boost numpy boost-python

我正在使用外部程序来计算用C++编写并与python通过接口的矩阵boost::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
Run Code Online (Sandbox Code Playgroud)

从我有限的理解,我相信问题X.__array_interface__是没有实际上没有返回任何东西().有没有办法np.array明确地传递这些参数或解决此问题.

我真的很擅长混合C++和python,如果这没有意义,或者我需要在任何部分阐述让我知道!

Ash*_*gar 3

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

print X.__array_interface__
#<bound method Matrix.__array_interface__ of <sprint.Matrix object at 0x107c5c320>>
Run Code Online (Sandbox Code Playgroud)

你有

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

另一种方法是定义一个自定义包装类:

class SprintMatrixWrapper(object):
    def __init__(self, sprint_matrix):
        self.__array_interface__ = sprint_matrix.__array_interface__()
Run Code Online (Sandbox Code Playgroud)

然后简单地做:

numpy.array(SprintMatrixWrapper(X))
Run Code Online (Sandbox Code Playgroud)