File IO between C/C++ libs and .NET Framework

From: Eat_My_Shortz (eatmyshortz_at_gmail.com)
Date: 02/28/05


Date: 28 Feb 2005 05:10:42 -0800

I'm trying to interoperate between file IO operations, on an open file,
between unmanaged C++ code and Managed C++, using the .NET framework.

Basically, at present, I have a C-style FILE* object, with an open
file. I would like to do some operations on this file, then while it's
still open, convert it into a .NET FileStream and do some processing
there.

I've noted that .NET's FileStream has a constructor:
public FileStream(IntPtr handle, System.IO.FileAccess access)
I assume the IntPtr argument is designed to interop with unmanaged
code. I've tried passing the FILE* in there, but get the error "The
handle is invalid" (Note this is a perfectly valid open file, opened
with fopen and can be read/written to using fread/fwrite/fgetc/fprintf,
etc).

So, next I go looking for the C++ library's file operations. I try some
sample code with the std::ofstream object:
    std::ofstream outData;

    outData.open("test.txt", ios::app);

    outData << "Hello World!" << endl;

    // Now add .NET Framework FileStream
    IntPtr odNet = IntPtr(&outData);

    FileStream* fs = new FileStream(odNet, FileAccess::Write);

Still the same: The Handle is invalid.

I've googled everywhere, and the most information anyone can provide on
this overload is that indeed, it does take an IntPtr, which is a Handle
to a file. Thanks a lot.

So, can anyone answer:
1. How do you get a Handle to a file, if this isnt the right way?
2. Can FileStream actually interop with C's FILE*?
3. Can FileStream actually interop with C++'s std::ofstream?
4. How do I "plug" it in?

Note: I'd really rather interop with C's FILE* if that's at all
possible, since I have a LOT of code using it.

If not, I assume I just have to store the file position, close the
file, then reopen it in .NET, and seek to that position again, right?
Annoying...
Thanks to anyone who replies.