Question

I'm writing a .NET adaptor for a C/C++ library where a method "bar" takes a regular stdio FILE*. Is it possible to build an interface so that managed code user can pass a managed (File)Stream? That is without creating an intermediary buffer and code to pipe the data between. Also does the assumption that bar() reads only make things any better?

// native code
void bar(FILE*);

// interface for managed code
void foo(System::IO::FileStream^ file)
{
    FILE* stdio_handle = ???;

    bar(stdio_handle);
}
Was it helpful?

Solution

System.IO.FileStream.Handle

It's not necessarily stdio handle. It's a Windows handle. I don't think FileStream is built upon stdio to have a stdio handle.

As Marc pointed out and mentioned in the MSDN link, you might want to consider using SafeFileHandle property (if you are on .NET 2.0+) instead of Handle (which is now considered obsolete). Only Handle is available in older versions, though.

OTHER TIPS

Is it possible to build an interface so that managed code user can pass a managed (File)Stream?

No, it's not possible to convert a stream to a file descriptor (FILE*).

If you have to have a stdio handle, you could always use fopen to open the file in the first place. This describes a wrapper to export the c stdlib file functions and then he uses interop to work with them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top