I'm trying to use Boost.Python as a wrapper for a C++ function that receives a pointer, modifies the data (managed on Python side as numpy array for example) and returns. How do I get Python numpy and Boost.Python to collaborate and to give me the raw pointer inside the function?
#include <boost/python.hpp>
namespace
{
char const *greet(double *p)
{
*p = 2.;
return "hello world";
}
}
BOOST_PYTHON_MODULE(module)
{
boost::python::def("greet", &greet);
}
In Python when I try,
import numpy as np
a = np.empty([2], dtype=np.double)
raw_ptr = a.data
print cmod.greet(raw_ptr)
I get the error,
Boost.Python.ArgumentError: Python argument types in
<...>.module.greet(buffer)
did not match C++ signature:
greet(double*)
One way that seems to work, suggested by Andreas Kloeckner, comments and alternatives are welcome. The greet() is modified as follows,
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";
}
in Python just use:
print cmod.greet(a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With