我正在尝试使用 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);
}
当我尝试使用 Python 时,
import numpy as np
a = np.empty([2], dtype=np.double)
raw_ptr = a.data
print cmod.greet(raw_ptr)
我得到了错误,
Boost.Python.ArgumentError: Python argument types in
<...>.module.greet(buffer)
did not match C++ signature:
greet(double*)
最佳答案
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";
}
在 Python 中只需使用:
print cmod.greet(a)
关于python - 如何将原始指针传递给 Boost.Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109336/