つまり、Boost.Pythonは移動セマンティクスをサポートしていないため、std::unique_ptr
をサポートしていません。 Boost.Pythonのnews/change logには、C++ 11の移動セマンティクスのために更新された兆候はありません。さらに、unique_ptr
サポートのこのfeature requestは、1年以上にわたって触れられていません。
しかし、Boost.Pythonは、std::auto_ptr
でPythonとの間でオブジェクトの排他的所有権を転送することをサポートしています。
- のPythonにC++の転送の所有権、C++の関数がなければなりません:
- を返す:
auto_ptr
介しインスタンスを受け入れます。 FAQは、manage_new_object
ポリシーでC++から返されたポインタは、std::auto_ptr
で管理されることに言及しています。 /// @brief Mockup Spam class.
struct Spam;
/// @brief Mockup factory for Spam.
struct SpamFactory
{
/// @brief Create Spam instances.
std::unique_ptr<Spam> make(const std::string&);
/// @brief Delete Spam instances.
void consume(std::unique_ptr<Spam>);
};
SpamFactory::make()
とSpamFactory::consume()
を経由してラップする必要があります
- を変更することはできませんAPI /ライブラリ考える
release()
経由unique_ptr
からauto_ptr
リリース制御を持っています補助機能。パイソンにC++から譲渡
機能を総称Python関数オブジェクトを作成する関数でラップすることができる:パイソンに
/// @brief Adapter a member function that returns a unique_ptr to
/// a python function object that returns a raw pointer but
/// explicitly passes ownership to Python.
template <typename T,
typename C,
typename ...Args>
boost::python::object adapt_unique(std::unique_ptr<T> (C::*fn)(Args...))
{
return boost::python::make_function(
[fn](C& self, Args... args) { return (self.*fn)(args...).release(); },
boost::python::return_value_policy<boost::python::manage_new_object>(),
boost::mpl::vector<T*, C&, Args...>()
);
}
ラムダ元の関数に委譲し、インスタンスのreleases()
所有権、および呼び出しポリシーは、Pythonがラムダから返された値の所有権を取得することを示します。 mpl::vector
はBoost.Pythonの呼び出しシグネチャを記述し、言語間の関数のディスパッチを適切に管理できるようにします。
adapt_unique
の結果はSpamFactory.make()
として公開されています
boost::python::class_<SpamFactory>(...)
.def("make", adapt_unique(&SpamFactory::make))
// ...
;
総称的にはSpamFactory::consume()
を適応させるには、より困難であるが、簡単な補助関数を記述するために十分に簡単です:
/// @brief Wrapper function for SpamFactory::consume_spam(). This
/// is required because Boost.Python will pass a handle to the
/// Spam instance as an auto_ptr that needs to be converted to
/// convert to a unique_ptr.
void SpamFactory_consume(
SpamFactory& self,
std::auto_ptr<Spam> ptr) // Note auto_ptr provided by Boost.Python.
{
return self.consume(std::unique_ptr<Spam>{ptr.release()});
}
補助機能Boost.Pythonによって提供されたauto_ptr
をAPIが要求するunique_ptr
に変換します。SpamFactory_consume
補助機能はSpamFactory.consume()
として公開されている:ここ
boost::python::class_<SpamFactory>(...)
// ...
.def("consume", &SpamFactory_consume)
;
は、完全なコードの例である:
#include <iostream>
#include <memory>
#include <boost/python.hpp>
/// @brief Mockup Spam class.
struct Spam
{
Spam(std::size_t x) : x(x) { std::cout << "Spam()" << std::endl; }
~Spam() { std::cout << "~Spam()" << std::endl; }
Spam(const Spam&) = delete;
Spam& operator=(const Spam&) = delete;
std::size_t x;
};
/// @brief Mockup factor for Spam.
struct SpamFactory
{
/// @brief Create Spam instances.
std::unique_ptr<Spam> make(const std::string& str)
{
return std::unique_ptr<Spam>{new Spam{str.size()}};
}
/// @brief Delete Spam instances.
void consume(std::unique_ptr<Spam>) {}
};
/// @brief Adapter a non-member function that returns a unique_ptr to
/// a python function object that returns a raw pointer but
/// explicitly passes ownership to Python.
template <typename T,
typename ...Args>
boost::python::object adapt_unique(std::unique_ptr<T> (*fn)(Args...))
{
return boost::python::make_function(
[fn](Args... args) { return fn(args...).release(); },
boost::python::return_value_policy<boost::python::manage_new_object>(),
boost::mpl::vector<T*, Args...>()
);
}
/// @brief Adapter a member function that returns a unique_ptr to
/// a python function object that returns a raw pointer but
/// explicitly passes ownership to Python.
template <typename T,
typename C,
typename ...Args>
boost::python::object adapt_unique(std::unique_ptr<T> (C::*fn)(Args...))
{
return boost::python::make_function(
[fn](C& self, Args... args) { return (self.*fn)(args...).release(); },
boost::python::return_value_policy<boost::python::manage_new_object>(),
boost::mpl::vector<T*, C&, Args...>()
);
}
/// @brief Wrapper function for SpamFactory::consume(). This
/// is required because Boost.Python will pass a handle to the
/// Spam instance as an auto_ptr that needs to be converted to
/// convert to a unique_ptr.
void SpamFactory_consume(
SpamFactory& self,
std::auto_ptr<Spam> ptr) // Note auto_ptr provided by Boost.Python.
{
return self.consume(std::unique_ptr<Spam>{ptr.release()});
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<Spam, boost::noncopyable>(
"Spam", python::init<std::size_t>())
.def_readwrite("x", &Spam::x)
;
python::class_<SpamFactory>("SpamFactory", python::init<>())
.def("make", adapt_unique(&SpamFactory::make))
.def("consume", &SpamFactory_consume)
;
}
インタラクティブなPython:
>>> import example
>>> factory = example.SpamFactory()
>>> spam = factory.make("a" * 21)
Spam()
>>> spam.x
21
>>> spam.x *= 2
>>> spam.x
42
>>> factory.consume(spam)
~Spam()
>>> spam.x = 100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
None.None(Spam, int)
did not match C++ signature:
None(Spam {lvalue}, unsigned int)
詳細な答えをありがとう!私はできるだけ早くこれを試すが、コードはよく見える! – schlimpf
そして、add_propertyとして定義されているstd :: unique_ptrはどうでしょうか?私は実際にプロパティを追加しているクラス定義、またはto_python_converterを定義する方がよい方法でしょうか? –