我想这应该很容易,但我做不到。我想打电话给
C++-function
来自python。作为论据我有一个
np-array
. 这个
C++
void foo_python(PyObject *p, const int m, const int n){
float *data = new float[m*n];
memcpy(data,PyArray_DATA(p),m*n*sizeof(float));
delete [] data;
}
当我从python调用它时
hello_ext.foo_python(A,A.shape[0], A.shape[1])
error: cannot convert âPyObject* {aka _object*}â to âPyArrayObject* {aka tagPyArrayObject*}â for argument â1â to âvoid* PyArray_DATA(PyArrayObject*)â
这以前很管用,但后来我把
#include <boost/python/numpy.hpp>
,这在我返回的函数中是必需的
ndarrays
np::ndarray test() {
int *data = new int[5];
for (int i = 0; i < 5; ++i){
data[i] = i+1;
}
p::tuple shape = p::make_tuple(5);
p::tuple stride = p::make_tuple(sizeof(int));
p::object own;
np::dtype dt = np::dtype::get_builtin<int>();
std::cout << " Here " << std::endl;
np::ndarray array = np::from_data(data, dt, shape, stride, own);
cout<<"Selective Multidimensional array :: "<<std::endl <<
p::extract<char const *>(p::str(array)) << std::endl;
// delete [] data;
return array;
}
这是模块:
BOOST_PYTHON_MODULE(libhello_ext)
{
using namespace boost::python;
Py_Initialize();
boost::python::numpy::initialize();
def("greet", greet);
def("sum", sum);
def("foo_python", foo_python);
def("test", test);
}