dqf2015 2015-10-03 21:00
浏览 72

如何使用SWIG和CGO将io.Reader转换为std :: istream?

I'm trying to use SWIG to create a Go wrapper for a C++ API that uses std::istream to read binary data. I'd like to be able to pass an io.Reader to these APIs, but I'm not sure how to create a mapping between it and std::istream. I know I need to implement a std::streambuf subclass and I assume the rest will involve directors and typemaps, but I'm not familiar enough with SWIG to figure out the right combination.

Any ideas?

  • 写回答

1条回答 默认 最新

  • dongroufan6846 2016-05-22 19:56
    关注

    io.Reader is too general to be passed to C functions -- it might not be backed on a real file at all (it's just a class that implements a Read(...) function)

    What you could do (so long as you aren't on windows) is use os.Pipe() to give you a ture FH object, but sadly the stock std::*stream doesn't have any way of creating a stream from an open file handle.

    The pipe bit looks something like this:

    func wrapReader(r io.Reader) uintptr {
        pr, pw, err := os.Pipe()
        if err != nil {
            panic(err)
        }
    
        go func () {
            _, _ io.Copy(pw, r)
            _ = pw.Close()
        }()
    
        return pr
    }
    

    If you combine that some of the code in this answer How to construct a c++ fstream from a POSIX file descriptor? you might get what you need

    评论

报告相同问题?