从 C++ 指针创建 ndarray
create ndarray out of c++ pointer
我用 C++ 创建了一个模块,需要使用 python 中的结果。
已经编写了一个包装器并且正在使用此代码
a = np.empty([r, hn])
for i in xrange(r):
for j in xrange(hn):
a[i,j]=self.thisptr.H[i*hn+j]
return a
代码可以运行,但我认为应该有一种更简单、更快速的方法来处理指针数据。
可悲的是,我不习惯 python 和 cython,我自己也弄不明白。
如有任何帮助,我们将不胜感激。 :)
Typed memoryviews (http://docs.cython.org/src/userguide/memoryviews.html) 是你的朋友。
a = np.empty([r,hn])
# interpret the array as a typed memoryview of shape (r, hn)
# and copy into a
# I've assumed the array is of type double* for the sake of answering the question
a[...] = <double[:r,:hn]>self.thisptr.H
它可能不会快很多(在内部它是一个与您编写的非常相似的循环),但它更容易。
或者,更简单,只需使用文档中的示例 (http://docs.cython.org/src/userguide/memoryviews.html#coercion-to-numpy)
a = np.asarray(<double[:r,:hn]>self.thisptr.H)
一种可能的方法是用 C 语言手动编写包装器。Python 对象的结构可以包含指向 C++ 对象的指针。查看我的代码(我在 2005 年做的),我发现我在需要 C++ 对象的 C 函数中测试了 NULL 并动态创建了它。
不错的副作用是您不必将所有 C++ 方法 1:1 公开给 Python,并且您可以调整界面以使其更 Pythonic。在我的包装器中,我在结构中存储了一些额外的信息,以便能够模拟 Python 列表行为并使将数据加载到 C++ 对象中更加高效。
我用 C++ 创建了一个模块,需要使用 python 中的结果。
已经编写了一个包装器并且正在使用此代码
a = np.empty([r, hn])
for i in xrange(r):
for j in xrange(hn):
a[i,j]=self.thisptr.H[i*hn+j]
return a
代码可以运行,但我认为应该有一种更简单、更快速的方法来处理指针数据。 可悲的是,我不习惯 python 和 cython,我自己也弄不明白。
如有任何帮助,我们将不胜感激。 :)
Typed memoryviews (http://docs.cython.org/src/userguide/memoryviews.html) 是你的朋友。
a = np.empty([r,hn])
# interpret the array as a typed memoryview of shape (r, hn)
# and copy into a
# I've assumed the array is of type double* for the sake of answering the question
a[...] = <double[:r,:hn]>self.thisptr.H
它可能不会快很多(在内部它是一个与您编写的非常相似的循环),但它更容易。
或者,更简单,只需使用文档中的示例 (http://docs.cython.org/src/userguide/memoryviews.html#coercion-to-numpy)
a = np.asarray(<double[:r,:hn]>self.thisptr.H)
一种可能的方法是用 C 语言手动编写包装器。Python 对象的结构可以包含指向 C++ 对象的指针。查看我的代码(我在 2005 年做的),我发现我在需要 C++ 对象的 C 函数中测试了 NULL 并动态创建了它。
不错的副作用是您不必将所有 C++ 方法 1:1 公开给 Python,并且您可以调整界面以使其更 Pythonic。在我的包装器中,我在结构中存储了一些额外的信息,以便能够模拟 Python 列表行为并使将数据加载到 C++ 对象中更加高效。