用docstring (boost:: Python)定义boost::函数
Define a boost::function with a docstring (Boost::Python)
我只是有一个函数对象:
boost::function<int(int)> func = /** ... **/;
并希望通过docstring将其公开给Python。
但显而易见的是:
def("func", func, "Some boring documentation goes here.");
失败,显示有趣的~2500行消息。
任何想法?
编辑:我做了其他测试:
def("func", func); // doesn't compile
def("func",
make_function(
func,
default_call_policies(),
vector<int,int>()
)
); // compiles
def("func",
make_function(
func,
default_call_policies(),
vector<int,int>()
),
"Some boring documentation goes here"
); // doesn't compile
boost::python::def()
文档提到只有在提供非空函数或成员函数指针时才能提供docstring。一种解决方案是将函数对象调用包装在函数中:
#include <boost/function.hpp>
#include <boost/python.hpp>
int times_two(int x) { return x * 2; }
boost::function<int(int)> func = ×_two;
int times_two_wrap(int x) { return func(x); }
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::def("times_two", ×_two_wrap,
"returns two times the supplied value");
}
互动用法:>>> import example
>>> assert(6 == example.times_two(3))
>>> print help(example.times_two)
times_two( (int)arg1) -> int :
returns two times the supplied value
C++ signature :
int times_two(int)
>>>
提振。Python有多个API层。最高层大部分都有文档,但它使用文档较少的低级API。在这种特殊情况下,看起来似乎高级API转发给低级API的效果很差。可以使用boost::python::make_function()
创建python函数,然后使用较低级别的boost::python::objects::add_to_namespace()
函数,如下所示:
#include <boost/function.hpp>
#include <boost/python.hpp>
int times_two(int x) { return x * 2; }
boost::function<int(int)> func = ×_two;
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
// Wrap the functor in a Python object.
python::object py_func = python::make_function(
func,
python::default_call_policies(),
boost::mpl::vector<int, int>());
// Add the function directly to the namespace.
python::objects::add_to_namespace(
python::scope(), // current namespace,
"times_two", // function name,
py_func, // function,
"returns two times the supplied value");
}
这会产生与交互使用相同的输出。这两种方法之间唯一值得注意的行为差异是,第一个示例允许在运行时通过向func
分配一个新值来更改底层实现。
相关文章:
- CMake 在 Windows 上的自定义位置上找不到 Boost
- 如何将来自 Boost.Python 的map_indexing_suite与自定义而不是标准对象一起使用?
- 告诉CMake链接到自定义文件夹中的Boost
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- Boost Python Numpy - 要初始化的未定义引用
- 使用自定义访问者时具有自定义类型的提升变体失败(源自 boost::static_visitor)
- boost::any 如何检查空值/未定义的值
- boost::asio 中的自定义处理程序
- 使用 Boost::Hana 中的 BOOST_HANA_DEFINE_STRUCT 定义具有 40 个以上字段的结构
- 如何使用boost定义布尔类,可能的值应该是TRUE或FALSE?
- 自定义预期失败的完整错误消息(boost::spirit::x3)
- boost::p rogram_options 自定义验证和默认值
- 如何在Boost::program_options配置文件中为非字符串的自定义选项值类型处理空格
- 如何修复架构x86_64的未定义符号,Boost Asio 1.58
- boost::asio::async_read_until 具有自定义匹配条件运算符重载混淆
- 使用 Boost/Python 的未定义符号 - 复杂
- 我仍然收到此错误未定义的引用:boost::log::v2_mt_posix::trivial::logger::get
- 将RFC5114中定义的 1024 位 P 和 G 值加载到 boost uint1024 中
- C++ Boost:在Windows中对boost::system::generic_category()的未定义引用
- 使用来自Python的boost定义的C++虚拟函数