如何将原始指针传递给 Boost.Python?
我正在尝试使用 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*)
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*)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
安德烈亚斯·克勒克纳(Andreas Kloeckner)建议的一种似乎有效的方法,欢迎评论和替代方案。 greet() 修改如下,
在 Python 中只需使用:
One way that seems to work, suggested by Andreas Kloeckner, comments and alternatives are welcome. The greet() is modified as follows,
in Python just use:
您可能需要使用 numpy ctypes 接口来获取指向存储的原始指针,然后将 ctypes 指针设置为 double 以传递到调用中。
ndarray.data
是缓冲区类型,而不是指针。我没有任何使用
boost.python
的经验,但我怀疑如果传递给需要指针作为参数的包装 C++ 函数,类似的东西会起作用。
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 likewill work if passed to a wrapped C++ function expecting a pointer as an argument.