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*)

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)

You will probably need to use the numpy ctypes interface to get a raw pointer to the storage, and then make a ctypes pointer to double to pass into the call. ndarray.data is a buffer type, not a pointer.

I don't have any experience with boost.python , but I suspect something like

In [28]: x=np.array([1,2,3,4],dtype=np.double)

In [29]: p=x.ctypes.data_as(ctypes.POINTER(ctypes.c_double))

In [30]: type(p)
Out[30]: <class 'ctypes.LP_c_double'>

will work if passed to a wrapped C++ function expecting a pointer as an argument.

链接地址: http://www.djcxy.com/p/9908.html

上一篇: 如何从Haskell中的文本块中提取关键字

下一篇: 如何将一个原始指针传递给Boost.Python?