Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a raw pointer to Boost.Python?

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*)
like image 959
rych Avatar asked Nov 13 '11 03:11

rych


1 Answers

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)
like image 118
rych Avatar answered Oct 16 '22 07:10

rych