我正在使用一个外部程序来计算一个用 C++ 编写并通过 boost::python
与 python 接口(interface)的矩阵。我想将此 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))
关于c++ - Numpy 的 __array_interface__ 不返回字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17753792/