ryc*_*ych 7 python pointers numpy boost-python
我正在尝试使用Boost.Python作为接收指针的C++函数的包装器,修改数据(例如在Python端托管为numpy数组)并返回.我如何让Python numpy和Boost.Python进行协作并在函数内部给出原始指针?
#include <boost/python.hpp>
namespace
{
char const *greet(double *p)
{
*p = 2.;
return "hello world";
}
}
BOOST_PYTHON_MODULE(module)
{
boost::python::def("greet", &greet);
}
Run Code Online (Sandbox Code Playgroud)
在Python中,当我尝试时,
import numpy as np
a = np.empty([2], dtype=np.double)
raw_ptr = a.data
print cmod.greet(raw_ptr)
Run Code Online (Sandbox Code Playgroud)
我收到错误,
Boost.Python.ArgumentError: Python argument types in
<...>.module.greet(buffer)
did not match C++ signature:
greet(double*)
Run Code Online (Sandbox Code Playgroud)
安德烈亚斯·克勒克纳(Andreas Kloeckner)建议的一种似乎有效的方法,欢迎评论和替代方案。greet() 修改如下,
char const *greet(boost::python::object obj) {
PyObject* pobj = obj.ptr();
Py_buffer pybuf;
if(PyObject_GetBuffer(pobj, &pybuf, PyBUF_SIMPLE)!=-1)
{
void *buf = pybuf.buf;
double *p = (double*)buf;
*p = 2.;
*(p+1) = 3;
PyBuffer_Release(&pybuf);
}
return "hello world";
}
Run Code Online (Sandbox Code Playgroud)
在Python中只需使用:
print cmod.greet(a)
Run Code Online (Sandbox Code Playgroud)