Technique for using std::ifstream, std::ofstream in python via SWIG?

后端 未结 5 1752
滥情空心
滥情空心 2021-01-12 09:16

Is there a way to use std::[io]fstream\'s in python via swig?

I have a c-class with functions like:

void readFrom(std::istream& istr         


        
5条回答
  •  自闭症患者
    2021-01-12 09:31

    I ended up just writing my own proxy class for use within the interface. So I used SWIG to wrap this class:

     /**
     * Simple class to expose std::streams in the python
     * interface.  works around some issues with trying to directy
     * the file stream objects
     */
    class ifstream_proxy: boost::noncopyable{
        public:
            ifstream_proxy(): m_istr(){
                // no op
            }
            virtual ~ifstream_proxy(){
                // no op
            }
            void open(const std::string& fname ){
                m_istr.close(); 
                m_istr.open( fname.c_str(), std::ifstream::in|std::ifstream::binary) ;
            }
            std::istream& stream(){
                return m_istr;
            }
            // TBD: do I want to  add additional stream manipulation functions?
       private: 
            std::ifstream m_istr;
    };
    

    and in python call make the calls

    >>> proxy=ifstream_proxy()
    >>> proxy.open('file_to_read_from.txt')
    >>> readFrom( stream_proxy.stream() )
    

提交回复
热议问题