简体   繁体   中英

How do I convert an io.Reader to a std::istream with SWIG & CGO?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM