在编写我的第一个django应用程序时,我遇到了以下关于boost::python的问题。从Python代码中,我需要将io.BytesIO传递给C++类,该类采用 STD::istRAM
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来说明这个问题。在
与其转换Python^{} 对象,不如考虑实现Boost.IOStreamsSource概念,能够从Python } ,并被{}使用。在
io.BytesIO
对象读取。这将允许一个人构造一个^{此tutorial演示如何创建和使用自定义Boost.IOStream公司来源。总的来说,这个过程应该相当直接。我们只需要根据^{} 实现源概念的
read()
函数:然后使用源设备创建
^{pr2}$boost::iostreams::stream
:由于
PythonInputDevice
是根据object.read()
实现的,duck typing允许PythonInputDevice
与任何支持read()
方法且具有相同前置和后置条件的Python对象一起使用。{a7>中的{a7>中不再需要在cd13}中包含条件分支。在以下是基于原始代码的完整最小示例:
交互式使用:
相关问题 更多 >
编程相关推荐