views:

151

answers:

3

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);
}
+5  A: 

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.

Mehrdad Afshari
taking not of the obsolescence remarks, etc - but +1
Marc Gravell
Valid concern. Updated the answer to reflect.
Mehrdad Afshari
A: 

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*).

eed3si9n
A: 

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.

R Ubben