我正在开发一个带有 Python 绑定(bind)(使用 boost::python)的 C++ 库,表示存储在文件中的数据。我的大多数半技术用户将使用 Python 与之交互,因此我需要使其尽可能 Pythonic。不过,我也会让 C++ 程序员使用 API,所以我不想在 C++ 方面妥协以适应 Python 绑定(bind)。
图书馆的很大一部分将由容器组成。为了让 python 用户更直观,我希望他们表现得像 python 列表,即:
# an example compound class
class Foo:
def __init__( self, _val ):
self.val = _val
# add it to a list
foo = Foo(0.0)
vect = []
vect.append(foo)
# change the value of the *original* instance
foo.val = 666.0
# which also changes the instance inside the container
print vect[0].val # outputs 666.0
测试设置
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <boost/python/register_ptr_to_python.hpp>
#include <boost/shared_ptr.hpp>
struct Foo {
double val;
Foo(double a) : val(a) {}
bool operator == (const Foo& f) const { return val == f.val; }
};
/* insert the test module wrapping code here */
int main() {
Py_Initialize();
inittest();
boost::python::object globals = boost::python::import("__main__").attr("__dict__");
boost::python::exec(
"import test\n"
"foo = test.Foo(0.0)\n" // make a new Foo instance
"vect = test.FooVector()\n" // make a new vector of Foos
"vect.append(foo)\n" // add the instance to the vector
"foo.val = 666.0\n" // assign a new value to the instance
// which should change the value in vector
"print 'Foo =', foo.val\n" // and print the results
"print 'vector[0] =', vect[0].val\n",
globals, globals
);
return 0;
}
shared_ptr
的方式
使用 shared_ptr,我可以获得与上面相同的行为,但这也意味着我必须使用共享指针在 C++ 中表示所有数据,从很多角度来看这并不好。
BOOST_PYTHON_MODULE( test ) {
// wrap Foo
boost::python::class_< Foo, boost::shared_ptr<Foo> >("Foo", boost::python::init<double>())
.def_readwrite("val", &Foo::val);
// wrap vector of shared_ptr Foos
boost::python::class_< std::vector < boost::shared_ptr<Foo> > >("FooVector")
.def(boost::python::vector_indexing_suite<std::vector< boost::shared_ptr<Foo> >, true >());
}
在我的测试设置中,这会产生与纯 Python 相同的输出:
Foo = 666.0
vector[0] = 666.0
vector<Foo>
的方式
直接使用 vector 在 C++ 端提供了一个很好的干净设置。但是,结果的行为方式与纯 Python 不同。
BOOST_PYTHON_MODULE( test ) {
// wrap Foo
boost::python::class_< Foo >("Foo", boost::python::init<double>())
.def_readwrite("val", &Foo::val);
// wrap vector of Foos
boost::python::class_< std::vector < Foo > >("FooVector")
.def(boost::python::vector_indexing_suite<std::vector< Foo > >());
}
这会产生:
Foo = 666.0
vector[0] = 0.0
这是“错误的”——改变原始实例并没有改变容器内的值。
我希望我不要太多
有趣的是,无论我使用两种封装中的哪一种,这段代码都有效:
footwo = vect[0]
footwo.val = 555.0
print vect[0].val
这意味着 boost::python 能够处理“假共享所有权”(通过其 by_proxy 返回机制)。在插入新元素时有什么方法可以达到同样的效果吗?
但是,如果答案是否定的,我很想听听其他建议 - Python 工具包中是否有一个示例实现了类似的集合封装,但它的行为不像 Python 列表?
非常感谢您阅读本文 :)
最佳答案
由于语言之间的语义差异,当涉及到集合时,通常很难将单个可重用的解决方案应用于所有场景。最大的问题是,虽然 Python 集合直接支持引用,但 C++ 集合需要一定程度的间接性,例如通过 shared_ptr
元素类型。如果没有这种间接,C++ 集合将无法支持与 Python 集合相同的功能。例如,考虑两个引用同一个对象的索引:
s = Spam()
spams = []
spams.append(s)
spams.append(s)
如果没有类似指针的元素类型,C++ 集合就不能有两个索引指向同一个对象。尽管如此,根据使用情况和需求,可能会有一些选项允许 Python 用户使用 Python 风格的接口(interface),同时仍保持 C++ 的单一实现。
- 最符合 Python 风格的解决方案是使用自定义转换器,将 Python 可迭代对象转换为 C++ 集合。见 this回答实现细节。如果出现以下情况,请考虑此选项:
- 集合的元素复制成本很低。
- C++ 函数仅对右值类型(即
std::vector<>
或const std::vector<>&
)进行操作。此限制阻止 C++ 更改 Python 集合或其元素。
- 增强
vector_indexing_suite
功能,尽可能多地重用功能,例如用于安全处理索引删除和底层集合重新分配的代理:- 使用自定义
HeldType
公开模型它用作智能指针并委托(delegate)给从vector_indexing_suite
返回的实例或元素代理对象. - Monkey 修补了将元素插入到集合中的集合方法,以便自定义
HeldType
将设置为委托(delegate)给元素代理。
- 使用自定义
当向 Boost.Python 公开一个类时,HeldType
是嵌入在 Boost.Python 对象中的对象类型。访问包装类型对象时,Boost.Python 调用 get_pointer()
对于HeldType
. object_holder
下面的类提供了将句柄返回到它拥有的实例或元素代理的能力:
/// @brief smart pointer type that will delegate to a python
/// object if one is set.
template <typename T>
class object_holder
{
public:
typedef T element_type;
object_holder(element_type* ptr)
: ptr_(ptr),
object_()
{}
element_type* get() const
{
if (!object_.is_none())
{
return boost::python::extract<element_type*>(object_)();
}
return ptr_ ? ptr_.get() : NULL;
}
void reset(boost::python::object object)
{
// Verify the object holds the expected element.
boost::python::extract<element_type*> extractor(object_);
if (!extractor.check()) return;
object_ = object;
ptr_.reset();
}
private:
boost::shared_ptr<element_type> ptr_;
boost::python::object object_;
};
/// @brief Helper function used to extract the pointed to object from
/// an object_holder. Boost.Python will use this through ADL.
template <typename T>
T* get_pointer(const object_holder<T>& holder)
{
return holder.get();
}
有了间接支持,剩下的唯一事情就是修补集合以设置 object_holder
.支持这一点的一种干净且可重复使用的方法是使用 def_visitor
.这是一个通用接口(interface),允许 class_
非侵入式扩展对象。例如,vector_indexing_suite
使用此功能。
custom_vector_indexing_suite
猴子下面的类修补append()
方法委托(delegate)给原始方法,然后调用 object_holder.reset()
使用新设置元素的代理。这导致 object_holder
引用集合中包含的元素。
/// @brief Indexing suite that will resets the element's HeldType to
/// that of the proxy during element insertion.
template <typename Container,
typename HeldType>
class custom_vector_indexing_suite
: public boost::python::def_visitor<
custom_vector_indexing_suite<Container, HeldType>>
{
private:
friend class boost::python::def_visitor_access;
template <typename ClassT>
void visit(ClassT& cls) const
{
// Define vector indexing support.
cls.def(boost::python::vector_indexing_suite<Container>());
// Monkey patch element setters with custom functions that
// delegate to the original implementation then obtain a
// handle to the proxy.
cls
.def("append", make_append_wrapper(cls.attr("append")))
// repeat for __setitem__ (slice and non-slice) and extend
;
}
/// @brief Returned a patched 'append' function.
static boost::python::object make_append_wrapper(
boost::python::object original_fn)
{
namespace python = boost::python;
return python::make_function([original_fn](
python::object self,
HeldType& value)
{
// Copy into the collection.
original_fn(self, value.get());
// Reset handle to delegate to a proxy for the newly copied element.
value.reset(self[-1]);
},
// Call policies.
python::default_call_policies(),
// Describe the signature.
boost::mpl::vector<
void, // return
python::object, // self (collection)
HeldType>() // value
);
}
};
包装需要在运行时进行,不能通过 def()
在类上直接定义自定义仿函数对象。 ,所以 make_function()
必须使用函数。对于仿函数,它需要 CallPolicies和 MPL front-extensible sequence代表签名。
这是一个完整的例子,demonstrates使用 object_holder
委托(delegate)给代理人和custom_vector_indexing_suite
修补集合。
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
/// @brief Mockup type.
struct spam
{
int val;
spam(int val) : val(val) {}
bool operator==(const spam& rhs) { return val == rhs.val; }
};
/// @brief Mockup function that operations on a collection of spam instances.
void modify_spams(std::vector<spam>& spams)
{
for (auto& spam : spams)
spam.val *= 2;
}
/// @brief smart pointer type that will delegate to a python
/// object if one is set.
template <typename T>
class object_holder
{
public:
typedef T element_type;
object_holder(element_type* ptr)
: ptr_(ptr),
object_()
{}
element_type* get() const
{
if (!object_.is_none())
{
return boost::python::extract<element_type*>(object_)();
}
return ptr_ ? ptr_.get() : NULL;
}
void reset(boost::python::object object)
{
// Verify the object holds the expected element.
boost::python::extract<element_type*> extractor(object_);
if (!extractor.check()) return;
object_ = object;
ptr_.reset();
}
private:
boost::shared_ptr<element_type> ptr_;
boost::python::object object_;
};
/// @brief Helper function used to extract the pointed to object from
/// an object_holder. Boost.Python will use this through ADL.
template <typename T>
T* get_pointer(const object_holder<T>& holder)
{
return holder.get();
}
/// @brief Indexing suite that will resets the element's HeldType to
/// that of the proxy during element insertion.
template <typename Container,
typename HeldType>
class custom_vector_indexing_suite
: public boost::python::def_visitor<
custom_vector_indexing_suite<Container, HeldType>>
{
private:
friend class boost::python::def_visitor_access;
template <typename ClassT>
void visit(ClassT& cls) const
{
// Define vector indexing support.
cls.def(boost::python::vector_indexing_suite<Container>());
// Monkey patch element setters with custom functions that
// delegate to the original implementation then obtain a
// handle to the proxy.
cls
.def("append", make_append_wrapper(cls.attr("append")))
// repeat for __setitem__ (slice and non-slice) and extend
;
}
/// @brief Returned a patched 'append' function.
static boost::python::object make_append_wrapper(
boost::python::object original_fn)
{
namespace python = boost::python;
return python::make_function([original_fn](
python::object self,
HeldType& value)
{
// Copy into the collection.
original_fn(self, value.get());
// Reset handle to delegate to a proxy for the newly copied element.
value.reset(self[-1]);
},
// Call policies.
python::default_call_policies(),
// Describe the signature.
boost::mpl::vector<
void, // return
python::object, // self (collection)
HeldType>() // value
);
}
// .. make_setitem_wrapper
// .. make_extend_wrapper
};
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
// Expose spam. Use a custom holder to allow for transparent delegation
// to different instances.
python::class_<spam, object_holder<spam>>("Spam", python::init<int>())
.def_readwrite("val", &spam::val)
;
// Expose a vector of spam.
python::class_<std::vector<spam>>("SpamVector")
.def(custom_vector_indexing_suite<
std::vector<spam>, object_holder<spam>>())
;
python::def("modify_spams", &modify_spams);
}
互动使用:
>>> import example
>>> spam = example.Spam(5)
>>> spams = example.SpamVector()
>>> spams.append(spam)
>>> assert(spams[0].val == 5)
>>> spam.val = 21
>>> assert(spams[0].val == 21)
>>> example.modify_spams(spams)
>>> assert(spam.val == 42)
>>> spams.append(spam)
>>> spam.val = 100
>>> assert(spams[1].val == 100)
>>> assert(spams[0].val == 42) # The container does not provide indirection.
作为 vector_indexing_suite
仍在使用,底层 C++ 容器只能使用 Python 对象的 API 进行修改。例如,调用 push_back
在容器上可能会导致底层内存的重新分配,并导致现有 Boost.Python 代理出现问题。另一方面,可以安全地修改元素本身,例如通过 modify_spams()
上面的函数。
关于python - 使用 boost::python vector_indexing_suite 包装 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27077518/