从 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
代码正在工作,但我认为应该有一种更简单、更快捷的方法来处理指针数据。可悲的是,我不习惯蟒蛇和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++ 对象中更有效率。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 从PyArray_SimpleNewFromData创建Numpy NDArray时出现问题
- 从 C++ 指针创建 ndArray