我如何在类中使用Boost包装的ofstream.Python到Python

How can i use ofstream in class that is wrapped with Boost.Python to Python?

本文关键字:Python 包装 Boost ofstream      更新时间:2023-10-16

我在一个月前更改了代码,我在下面描述的相同错误中卡住了。我找不到一个非常简单的例子,如何使用Boost公开一个fstream对象。Python到Python来解决我解释的问题

简而言之,我只是想公开一个类,它包含一个i/O对象与函数写/打开/关闭。在Pyton中,我想执行以下步骤:

    开放File1
  1. 开放File2
  2. 开放File3
  3. 写入文件1
  4. 写入文件2
  5. 写入文件
  6. 关闭文件

C/c++代码

////// I N C L U D E S //////
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python.hpp>
#include <fstream>
#include <string.h>
////////////////////////////

using namespace std;
struct BoostXML_IO
{
    ofstream File;
    void writeFile(const string& strToWrite)
    {
        this->File.write(strToWrite.data(), strToWrite.size());
    }
    void openFile(const string& path)
    {
        this->File.open(path, ios::app);
    }
    void closeFile()
    {
        this->File.close();
    }
};

BOOST_PYTHON_MODULE(BoostXML_IO)
{
    using namespace boost::python;  
    class_<BoostXML_IO, boost::noncopyable>("BoostXML_IO")
      .def("writeFile", &BoostXML_IO::writeFile)
      .def("openFile", &BoostXML_IO::openFile)
      .def("closeFile", &BoostXML_IO::closeFile)
    ;
}

这段代码总是编译没有错误,但最后在Python中,当我试图调用提示行中的一个函数时,我总是得到以下错误:

错误代码

>>> import BoostXML_IO
>>> File1 = BoostXML_IO
>>> File = BoostXML_IO.BoostXML_IO.openFileFailed to format the args
Traceback (most recent call last):
  File "C:apptoolsPython25Libsite-packagespythonwinpywinidleCallTips.py", line 130, in get_arg_text
    argText = inspect.formatargspec(*arg_getter(fob))
  File "C:apptoolsPython25Libinspect.py", line 743, in getargspec
    raise TypeError('arg is not a Python function')
TypeError: arg is not a Python function
(

提前感谢!

你的编译错误与Boost.Python无关。首先包括<string><ofstream>,然后添加using namespace std;。这应该可以修复你得到的大多数错误。然后像这样修复你的结构声明:

struct BoostXML_IO
{    
  void openFile(const string& path)
  {
    myfile.open(path);
  }
  void closeFile()
  {
    myfile.close();
  }
  void WriteToFile(const char* strToWrite)
  {
    myfile.write(strToWrite, strlen(strToWrite));
  }
private:
  ofstream myFile;
};

我也不认为需要在openFileWriteToFile中作为参数传递strToWritepath成员时设置一个读写引用。


EDIT这个呢:

struct BoostXML_IO
{
    BoostXML_IO()
    {}
    void writeFile(const string& strToWrite)
    {
        File.write(strToWrite.data(), strToWrite.size());
    }
    void openFile(const string& path)
    {
        File.open(path, ios::out);
    }
    void closeFile()
    {
        File.close();
    }
private:
    BoostXML_IO(const BoostXML_IO&);
    BoostXML_IO& operator=(const BoostXML_IO&);
    ofstream File;
};

BOOST_PYTHON_MODULE(BoostXML_IO)
{
    using namespace boost::python;  
    class_<BoostXML_IO>("BoostXML_IO", init<>())
      .def("writeFile", &BoostXML_IO::writeFile)
      .def("openFile", &BoostXML_IO::openFile)
      .def("closeFile", &BoostXML_IO::closeFile)
    ;
}

我不知道为什么你想要暴露一个ofstream到python API。在openFile中指定文件路径时,pathToFile变量也是如此。但是我想我已经提到过了