转换Python.io在使用boost::python时将对象转换为std::istream

2024-10-04 03:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在编写我的第一个django应用程序时,我遇到了以下关于boost::python的问题。从Python代码中,我需要将io.BytesIO传递给C++类,该类采用 STD::istRAM。在

<>我有一个传统的C++库,用于读取某种格式的文件。让我们称之为somelib。这个库的接口使用std::istream作为输入。像这样:

class SomeReader
{
public:
    bool read_from_stream(std::istream&);
};

我想把它包装起来,这样我就可以用python中的lib,方法如下:

^{pr2}$

我了解了如何对实际的python文件对象执行此操作。但是,对于任意的文件类的对象,如何做还不清楚。这是迄今为止我所拥有的python绑定的定义:

using namespace boost::python;
namespace io = boost::iostreams;

struct SomeReaderWrap: SomeReader, wrapper<SomeReader>
{
    bool read(object &py_file)
    {
        if (PyFile_Check(py_file.ptr()))
        {
            FILE* handle = PyFile_AsFile(py_file.ptr());
            io::stream_buffer<io::file_descriptor_source> fpstream (fileno(handle), io::never_close_handle);
            std::istream in(&fpstream);
            return this->read_from_stream(in);
        }
        else
        {
            //
            // How do we implement this???
            //
            throw std::runtime_error("Not a file, have no idea how to read this!");
        }
    }
};


BOOST_PYTHON_MODULE(somelib)
{
    class_<SomeReaderWrap, boost::noncopyable>("SomeReader")
        .def("read", &SomeReaderWrap::read);
}

有没有一种大致的将Python IO对象转换成C++流的方法?在

提前谢谢你。在


作为实验的结果,我创建了一个小的github repo来说明这个问题。在


Tags: 文件对象pyioreadstreamthisfile
1条回答
网友
1楼 · 发布于 2024-10-04 03:16:20

与其转换Python^{}对象,不如考虑实现Boost.IOStreamsSource概念,能够从Python io.BytesIO对象读取。这将允许一个人构造一个^{},并被{}使用。在

tutorial演示如何创建和使用自定义Boost.IOStream公司来源。总的来说,这个过程应该相当直接。我们只需要根据^{}实现源概念的read()函数:

/// Type that implements the Boost.IOStream's Source concept for reading
/// data from a Python object supporting read(size).
class PythonInputDevice
  : public boost::iostreams::source // Use convenience class.
{
public:

  explicit
  PythonInputDevice(boost::python::object object)
    : object_(object)
  {}

  std::streamsize read(char_type* buffer, std::streamsize buffer_size) 
  {
    namespace python = boost::python;
    // Read data through the Python object's API.  The following is
    // is equivalent to:
    //   data = object_.read(buffer_size)
    boost::python::object py_data = object_.attr("read")(buffer_size);
    std::string data = python::extract<std::string>(py_data);

    // If the string is empty, then EOF has been reached.
    if (data.empty())
    {
      return -1; // Indicate end-of-sequence, per Source concept.
    }

    // Otherwise, copy data into the buffer.
    copy(data.begin(), data.end(), buffer);
    return data.size();
  }

private:
  boost::python::object object_;
};

然后使用源设备创建boost::iostreams::stream

^{pr2}$

由于PythonInputDevice是根据object.read()实现的,duck typing允许PythonInputDevice与任何支持read()方法且具有相同前置和后置条件的Python对象一起使用。{a7>中的{a7>中不再需要在cd13}中包含条件分支。在


以下是基于原始代码的完整最小示例:

#include <algorithm> // std::copy
#include <iosfwd> // std::streamsize
#include <iostream>
#include <boost/python.hpp>
#include <boost/iostreams/concepts.hpp>  // boost::iostreams::source
#include <boost/iostreams/stream.hpp>

class SomeReader
{
public:
  bool read_from_stream(std::istream& input)
  {
    std::string content(std::istreambuf_iterator<char>(input.rdbuf()),
                        (std::istreambuf_iterator<char>()));
    std::cout << "SomeReader::read_from_stream(): " << content << std::endl;
    return true;      
  }
};

/// Type that implements a model of the Boost.IOStream's Source concept
/// for reading data from a Python object supporting:
///   data = object.read(size).
class PythonInputDevice
  : public boost::iostreams::source // Use convenience class.
{
public:

  explicit
  PythonInputDevice(boost::python::object object)
    : object_(object)
  {}

  std::streamsize read(char_type* buffer, std::streamsize buffer_size) 
  {
    namespace python = boost::python;
    // Read data through the Python object's API.  The following is
    // is equivalent to:
    //   data = object_.read(buffer_size)
    boost::python::object py_data = object_.attr("read")(buffer_size);
    std::string data = python::extract<std::string>(py_data);

    // If the string is empty, then EOF has been reached.
    if (data.empty())
    {
      return -1; // Indicate end-of-sequence, per Source concept.
    }

    // Otherwise, copy data into the buffer.
    copy(data.begin(), data.end(), buffer);
    return data.size();
  }

private:
  boost::python::object object_;
};

struct SomeReaderWrap
  : SomeReader,
    boost::python::wrapper<SomeReader>
{
  bool read(boost::python::object& object)
  {
    boost::iostreams::stream<PythonInputDevice> input(object);
    return this->read_from_stream(input);
  }
};

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<SomeReaderWrap, boost::noncopyable>("SomeReader")
    .def("read", &SomeReaderWrap::read)
    ;
}

交互式使用:

$ echo -n "test file" > test_file
$ python
>>> import example
>>> with open('test_file') as f:
...     reader = example.SomeReader()
...     reader.read(f)
... 
SomeReader::read_from_stream(): test file
True
>>> import io
>>> with io.BytesIO("Hello Stack Overflow") as f:
...     reaader = example.SomeReader()
...     reader.read(f)
... 
SomeReader::read_from_stream(): Hello Stack Overflow
True

相关问题 更多 >