boost :: python传递python :: list的引用

Chr*_*s S 3 c++ python boost reference boost-python

我真的很想知道是否有可能将python列表的引用传递给boost :: python c ++ dll.我想要实现的是我在python中有一个列表,可以随时用c ++读取.假设你在C++中有一个变量来保存对列表的引用.

有没有办法做到这一点?到目前为止,我只在python中找到了ctypes,我可以在其中引用原始c类型,在这种情况下,它没有帮助.

我很高兴任何建议或解决方法(一个简单的例子会很棒)

问候克里斯

Tan*_*ury 7

简而言之,Boost.Python使用TypeWrappers维护Python参数传递语义.因此,当将Python中的列表传递给公开的C++函数时,可以通过接受Python列表作为boost::python::list对象来创建和维护引用.


详细的答案实际上有一点深度.在深入研究之前,让我扩展一些语义以避免混淆.使用Python的垃圾收集和传递对象语义,一般的经验法则是将Boost.Python TypeWrappers视为智能指针.

  • 如果函数接受列表作为boost::python::list对象,则C++现在具有对Python对象的引用.Python列表的生命周期将至少与booot::python::list对象一样长.
  • 如果Python列表转换为其他类型,例如std::vector,则C++已经为Python列表构建了一个副本.此副本与原始列表无关.

下面是一个C++模块的简单示例,可以传递Python列表,维护它的句柄并打印其内容:

#include <iostream> // std::cout
#include <utility>  // std::make_pair
#include <boost/foreach.hpp>
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>

boost::python::list list;

/// @brief Store handle to the list.
///
/// @param pylist Python list for which a handle will be maintained.
void set(const boost::python::list& pylist)
{
  // As the boost::python::list object is smart-pointer like, this
  // creates a reference to the python list, rather than creating a 
  // copy of the python list.
  list = pylist;
}

// Iterate over the current list, printing all ints.
void display()
{
  std::cout << "in display" << std::endl;
  typedef boost::python::stl_input_iterator<int> iterator_type;
  BOOST_FOREACH(const iterator_type::value_type& data, 
                std::make_pair(iterator_type(list), // begin
                               iterator_type()))    // end
  {
    std::cout << data << std::endl;
  }
}

BOOST_PYTHON_MODULE(example) {
  namespace python = boost::python;
  python::def("set",     &set);
  python::def("display", &display);
}
Run Code Online (Sandbox Code Playgroud)

它的用法:

>>> import example
>>>
>>> x = range(2)
>>> x
[0, 1]
>>> example.set(x)
>>> example.display()
in display
0
1
>>> x[:] = range(7, 10)
>>> example.display()
in display
7
8
9
Run Code Online (Sandbox Code Playgroud)

一个在问题带来的复杂性是阅读在C Python列表++的愿望任何时候.在最复杂的情​​况下,任何时间都可以在C++线程中的任何时间发生.

让我们从基础开始:Python的全局解释器锁(GIL).简而言之,GIL是解释器周围的互斥体.如果一个线程正在做任何影响python托管对象的引用计数的事情,那么它需要获得GIL.有时引用计数不是很透明,请考虑:

typedef boost::python::stl_input_iterator<int> iterator_type;
iterator_type iterator(list);
Run Code Online (Sandbox Code Playgroud)

虽然boost::python::stl_input_iterator接受list作为常量引用,但它从构造函数中创建对Python列表的引用.

在前面的示例中,由于没有C++线程,因此在获取GIL时发生了所有操作.但是,如果display()可以在C++中随时调用,则需要进行一些设置.

首先,模块需要让Python初始化GIL以进行线程化.

BOOST_PYTHON_MODULE(example) {
  PyEval_InitThreads(); // Initialize GIL to support non-python threads.
  ...
}
Run Code Online (Sandbox Code Playgroud)

为方便起见,我们创建一个简单的类来帮助管理GIL:

/// @brief RAII class used to lock and unlock the GIL.
class gil_lock
{
public:
  gil_lock()  { state_ = PyGILState_Ensure(); }
  ~gil_lock() { PyGILState_Release(state_);   }
private:
  PyGILState_STATE state_;
};
Run Code Online (Sandbox Code Playgroud)

为了显示与C++线程的交互,我们可以向模块添加功能,以允许应用程序安排显示列表内容的延迟.

/// @brief Entry point for delayed display thread.
///
/// @param Delay in seconds.
void display_in_main(unsigned int seconds)
{
  boost::this_thread::sleep_for(boost::chrono::seconds(seconds));
  gil_lock lock; // Acquire GIL.
  display();     // Can safely modify python objects.
  // GIL released when lock goes out of scope.
}

/// @brief Schedule the list to be displayed.
///
/// @param Delay in seconds.
void display_in(unsigned int seconds)
{
  // Start detached thread.
  boost::thread(&display_in_main, seconds).detach();
}
Run Code Online (Sandbox Code Playgroud)

这是完整的例子:

#include <iostream> // std::cout
#include <utility>  // std::make_pair
#include <boost/foreach.hpp>
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include <boost/thread.hpp>

boost::python::list list;

/// @brief Store handle to the list.
///
/// @param pylist Python list for which a handle will be maintained.
void set(const boost::python::list& pylist)
{
  list = pylist;
}

// Iterate over the current list, printing all ints.
void display()
{
  std::cout << "in display" << std::endl;
  typedef boost::python::stl_input_iterator<int> iterator_type;
  BOOST_FOREACH(const iterator_type::value_type& data, 
                std::make_pair(iterator_type(list), // begin
                               iterator_type()))    // end
  {
    std::cout << data << std::endl;
  }
}

/// @brief RAII class used to lock and unlock the GIL.
class gil_lock
{
public:
  gil_lock()  { state_ = PyGILState_Ensure(); }
  ~gil_lock() { PyGILState_Release(state_);   }
private:
  PyGILState_STATE state_;
}; 

/// @brief Entry point for delayed display thread.
///
/// @param Delay in seconds.
void display_in_main(unsigned int seconds)
{
  boost::this_thread::sleep_for(boost::chrono::seconds(seconds));
  gil_lock lock; // Acquire GIL.
  display();     // Can safely modify python objects.
  // GIL released when lock goes out of scope.
}

/// @brief Schedule the list to be displayed.
///
/// @param Delay in seconds.
void display_in(unsigned int seconds)
{
  // Start detached thread.
  boost::thread(&display_in_main, seconds).detach();
}

BOOST_PYTHON_MODULE(example) {
  PyEval_InitThreads(); // Initialize GIL to support non-python threads.

  namespace python = boost::python;
  python::def("set",        &set);
  python::def("display",    &display);
  python::def("display_in", &display_in);
}
Run Code Online (Sandbox Code Playgroud)

它的用法:

>>> import example
>>> from time import sleep
>>> 
>>> x = range(2)
>>> example.set(x)
>>> example.display()
in display
0
1
>>> example.display_in(3)
>>> x[:] = range(7, 10)
>>> print "sleeping"
sleeping
>>> sleep(6)
in display
7
8
9
Run Code Online (Sandbox Code Playgroud)

当Python控制台在sleep(6)调用中被阻塞6秒时,C++线程获取了GIL,显示了list的内容x,并释放了GIL.