c++ - Numpy 的 __array_interface__ 不返回字典

标签 c++ python boost numpy boost-python

我正在使用一个外部程序来计算一个用 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/

相关文章:

android - 如何使用 logcat 在 native 代码中打印(或转储)包裹?

c++ - scoped_lock 的范围

c++ - 复变量函数的自动微分

python - 如何使用 PyQt 使用 python 打印包含特殊字符的 QString?

python - 从 10-K -- 提取 SIC、CIK,创建元数据表

Python Pandas - 根据值删除行

c++ - BOOST_TYPEOF 返回 int 而不是 const int

c++ - 这个 C++/C++11 结构是什么意思?

c++ - 通用/模板编程最佳实践 : To limit types, 或不限制类型

c++ - 模板别名在模板类模板方法的参数中不起作用