Search code examples
c#.netdllfile-handlingcrt

Get a FILE* handle to be passed to a C function for System.IO.File and default streams


I'm using an old C library (built as a DLL) within my C# application. One of the functions in this library requires a FILE* (as defined in ANSI C) to be passed. Is there any way I can get a FILE* handle, in C#, for a System.IO.File, stdout and stderr?

Or is there any way to workaround this problem, any idea, hint, etc...?

Thanks in advance.


Solution

  • I haven't tried this, but it might work...

    System.IO.File.Create()/Open() will return a FileStream, from there you can use FileStream.SafeFileHandle and from there SafeFileHandle.DangerousGetHandle() will give you the native operating system HANDLE.

    Then in unmanaged C, _open_osfhandle() will take your HANDLE and return an int file descripter. Pass this to _fdopen() and it will return a FILE*.

    A long route, with plenty of opportunity for incompatibilities and other gotchas. But you might be lucky!