简体   繁体   English

如何将原始指针传递给Boost.Python?

[英]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. 我正在尝试使用Boost.Python作为接收指针的C ++函数的包装器,修改数据(例如在Python端托管为numpy数组)并返回。 How do I get Python numpy and Boost.Python to collaborate and to give me the raw pointer inside the function? 我如何让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);
}

In Python when I try, 在Python中,当我尝试时,

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. Andreas Kloeckner建议的一种似乎有效的方法,欢迎评论和替代方案。 The greet() is modified as follows, 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";
    }

in Python just use: 在Python中使用:

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. 您可能需要使用numpy ctypes接口来获取指向存储的原始指针,然后将ctypes指针设置为double以传递给调用。 ndarray.data is a buffer type, not a pointer. ndarray.data是缓冲区类型,而不是指针。

I don't have any experience with boost.python , but I suspect something like 我对boost.python没有任何经验,但我怀疑有类似的东西

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. 如果传递给一个期望指针作为参数的包装C ++函数,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM