P/Invoke and FILE*

  • Thread starter Thread starter SamoK
  • Start date Start date
S

SamoK

Hy!

I have to invoke a function that has a FILE pointer for its parameter.
e.g.
int myfunct(FILE *f);

Does anyone know how can P/Invoke such function? And would it be possible to
pass StreamReader as a parameter to an invoked function (I know it is not
possible to do so directly)?


Thanks in advance
- Samo
 
Does anyone know how can P/Invoke such function?

Well first you have to aquire a FILE* from some function that uses the
same C runtime library as the DLL containing myfunc.

And would it be possible to
pass StreamReader as a parameter to an invoked function (I know it is not
possible to do so directly)?

Not directly, no.



Mattias
 
I have to invoke a function that has a FILE pointer for its parameter.
e.g.
int myfunct(FILE *f);

The FILE structure is (AFAIK) an internal of the standard C library, so you
won't be able to recreate it in C#. I think it can even differ between
debug/release or single-threaded/multi-threaded build. Best way to go is
probably building a wrapper in managed C++.
Does anyone know how can P/Invoke such function? And would it be possible to
pass StreamReader as a parameter to an invoked function (I know it is not
possible to do so directly)?

I think there are microsoft-specific C functions that enable you to create a
FILE from a win32 HANDLE. Maybe you can create an unnamed pipe, connect one
end to the FILE, and another to your StreamReader.
Of course, this only works if your C-function treats the file as a stream,
too (i.e. doesn't reposition the file pointer)

Niki
 
Oh my... whole bunch of stuff... :)
I think it would be beteer to dig in and rewrite this one in pure C# since
this wouldn be such on overkill.
;)

But thanks for your help.
 
Hy!

I have to invoke a function that has a FILE pointer for its parameter.
e.g.
int myfunct(FILE *f);

Does anyone know how can P/Invoke such function? And would it be possible to
pass StreamReader as a parameter to an invoked function (I know it is not
possible to do so directly)?


Thanks in advance
- Samo

Well, treat the FILE pointer in C# as an IntPtr. You can then import
such function using C# P/Invoke like so:

[ DllImport("YourLibrary.dll") ]
public static extern int myfunct(IntPtr filehandle);

Of course, you also need some other function the returns an usable
FILE* handle for you (I quickly made this up, dunno if it actually
works):

[ DllImport("msvcrt.dll", CharSet=CharSet.Auto) ]
public static extern IntPtr fopen(string file, string mode);
 
Back
Top