我将把一个c++
数组作为numpy array
发送给一个python函数,并返回另一个numpy array
。在查阅了numpy
文档和其他一些线程并对代码进行了调整之后,代码终于可以工作了,但是我想知道,考虑到以下几点,这段代码的编写是否是最佳的:
c++
和numpy (python)
之间不必要地复制数组。C++代码:
// python_embed.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "Python.h"
#include "numpy/arrayobject.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Py_SetProgramName(argv[0]);
Py_Initialize();
import_array()
// Build the 2D array
PyObject *pArgs, *pReturn, *pModule, *pFunc;
PyArrayObject *np_ret, *np_arg;
const int SIZE{ 10 };
npy_intp dims[2]{SIZE, SIZE};
const int ND{ 2 };
long double(*c_arr)[SIZE]{ new long double[SIZE][SIZE] };
long double* c_out;
for (int i{}; i < SIZE; i++)
for (int j{}; j < SIZE; j++)
c_arr[i][j] = i * SIZE + j;
np_arg = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, dims, NPY_LONGDOUBLE,
reinterpret_cast<void*>(c_arr)));
// Calling array_tutorial from mymodule
PyObject *pName = PyUnicode_FromString("mymodule");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (!pModule){
cout << "mymodule can not be imported" << endl;
Py_DECREF(np_arg);
delete[] c_arr;
return 1;
}
pFunc = PyObject_GetAttrString(pModule, "array_tutorial");
if (!pFunc || !PyCallable_Check(pFunc)){
Py_DECREF(pModule);
Py_XDECREF(pFunc);
Py_DECREF(np_arg);
delete[] c_arr;
cout << "array_tutorial is null or not callable" << endl;
return 1;
}
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs, 0, reinterpret_cast<PyObject*>(np_arg));
pReturn = PyObject_CallObject(pFunc, pArgs);
np_ret = reinterpret_cast<PyArrayObject*>(pReturn);
if (PyArray_NDIM(np_ret) != ND - 1){ // row[0] is returned
cout << "Function returned with wrong dimension" << endl;
Py_DECREF(pFunc);
Py_DECREF(pModule);
Py_DECREF(np_arg);
Py_DECREF(np_ret);
delete[] c_arr;
return 1;
}
int len{ PyArray_SHAPE(np_ret)[0] };
c_out = reinterpret_cast<long double*>(PyArray_DATA(np_ret));
cout << "Printing output array" << endl;
for (int i{}; i < len; i++)
cout << c_out[i] << ' ';
cout << endl;
// Finalizing
Py_DECREF(pFunc);
Py_DECREF(pModule);
Py_DECREF(np_arg);
Py_DECREF(np_ret);
delete[] c_arr;
Py_Finalize();
return 0;
}
在CodeReview中,有一个极好的答案:Link...
试试xtensor和xtensor-pythonpython绑定
XTUNSOR是一种用于多维数组表达式的数值分析的C++库。
xtensor提供
使用示例
初始化二维数组并计算其中一行和一维数组的和。
输出
< H2>在C++中创建一个简单的通用函数Python代码:
输出
另一种方法是,在不直接接触Python C API的情况下,可以使用pybind11(仅头库):
CPP:
在
py_test.py
中:输出:
请参阅official documentation。
ps:我使用C++的A{A3}。
从我的经验来看,这似乎是相当有效的。 为了获得更高的效率,请尝试以下操作: http://ubuntuforums.org/showthread.php?t=1266059
使用编织,可以在Python中嵌入C/C++代码,这样可能会有用。
http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.weave.inline.html
下面是一个关于如何使用Python在多种语言之间进行接口的链接以及一些示例。
http://docs.scipy.org/doc/numpy/user/c-info.python-as-glue.html
这是一个如何使用Cython将numpy数组传递给c++的简单快速的示例:
http://www.birving.com/blog/2014/05/13/passing-numpy-arrays-between-python-and/
相关问题 更多 >
编程相关推荐