Mar*_*zak 17 c++ python boost-python
我正在使用Python绑定(使用boost :: python)表示存储在文件中的数据的C++库.我的大多数半技术用户将使用Python与之交互,因此我需要尽可能将其设为Pythonic.但是,我也会让C++程序员使用API,所以我不想在C++方面妥协以适应Python绑定.
图书馆的很大一部分将由容器制成.为了让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
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
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 >());
}
Run Code Online (Sandbox Code Playgroud)
在我的测试设置中,这产生与纯Python相同的输出:
Foo = 666.0
vector[0] = 666.0
Run Code Online (Sandbox Code Playgroud)
vector<Foo>直接使用向量可以在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 > >());
}
Run Code Online (Sandbox Code Playgroud)
这会产生:
Foo = 666.0
vector[0] = 0.0
Run Code Online (Sandbox Code Playgroud)
哪个是"错误的" - 更改原始实例并未更改容器内的值.
有趣的是,无论我使用哪两种封装,这段代码都能正常工作:
footwo = vect[0]
footwo.val = 555.0
print vect[0].val
Run Code Online (Sandbox Code Playgroud)
这意味着boost :: python能够处理"假共享所有权"(通过其by_proxy返回机制).插入新元素时有没有办法实现同样的目标?
但是,如果答案是否定的,我很乐意听到其他建议 - Python工具包中是否有一个示例,其中实现了类似的集合封装,但它不像python列表那样?
非常感谢你阅读这篇文章:)
由于语言之间的语义差异,当涉及集合时,将单个可重用解决方案应用于所有场景通常非常困难。最大的问题是,虽然 Python 集合直接支持引用,但 C++ 集合需要一定程度的间接,例如通过shared_ptr元素类型。如果没有这种间接,C++ 集合将无法支持与 Python 集合相同的功能。例如,考虑引用同一对象的两个索引:
s = Spam()
spams = []
spams.append(s)
spams.append(s)
Run Code Online (Sandbox Code Playgroud)
如果没有类似指针的元素类型,C++ 集合就不能有两个引用同一对象的索引。然而,根据使用情况和需求,可能有一些选项允许为 Python 用户提供类似 Python 的界面,同时仍然保持 C++ 的单一实现。
std::vector<>or const std::vector<>&)进行操作。此限制阻止 C++ 对 Python 集合或其元素进行更改。vector_indexing_suite功能,重用尽可能多的功能,例如用于安全处理索引删除和底层集合重新分配的代理:
HeldType,并将其委托给从 返回的实例或元素代理对象vector_indexing_suite。HeldType将自定义设置为委托给元素代理。将类公开给 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();
}
Run Code Online (Sandbox Code Playgroud)
在支持间接寻址的情况下,唯一剩下的就是修补集合以设置object_holder. 支持这一点的一种干净且可重用的方法是使用def_visitor. 这是一个通用接口,允许以class_非侵入方式扩展对象。例如,vector_indexing_suite使用此功能。
下面的类custom_vector_indexing_suite猴子修补append()方法以委托给原始方法,然后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
);
}
};
Run Code Online (Sandbox Code Playgroud)
包装需要在运行时进行,并且自定义函子对象不能通过 via 直接在类上定义def(),因此make_function()必须使用该函数。对于函子,它需要CallPolicies和表示签名的MPL 前端可扩展序列。
这是一个完整的示例,演示了如何使用object_holder委托代理和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);
}
Run Code Online (Sandbox Code Playgroud)
互动使用:
>>> 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.
Run Code Online (Sandbox Code Playgroud)
由于vector_indexing_suite仍在使用,底层 C++ 容器只能使用 Python 对象的 API 进行修改。例如,调用push_back容器可能会导致底层内存的重新分配,并导致现有的 Boost.Python 代理出现问题。另一方面,可以安全地修改元素本身,例如通过modify_spams()上面的函数完成的操作。
| 归档时间: |
|
| 查看次数: |
5788 次 |
| 最近记录: |