2

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.

PJTraill
  • 1,353
  • 12
  • 30
gd1
  • 11,300
  • 7
  • 49
  • 88

1 Answers1

2

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!

Ciaran Keating
  • 2,793
  • 21
  • 19
  • I see. I'll think about dropping that DLL. Thank you – gd1 Mar 22 '11 at 21:56
  • 1
    Is that because it's just too much trouble? (Not an unreasonable view: you'd have to interpose a new C DLL between your C# app and the old DLL, among other stuff.) Or did you try it and find that it doesn't work? – Ciaran Keating Mar 23 '11 at 01:00
  • I thought about dropping the DLL and rewriting everything in C#, but I've found the original C source of that DLL (quite old, indeed) and edited it so that it doesn't need the use of a FILE*, but just a char* which contains the path to the file. So the C DLL creates, opens, writes and closes the file itself. It was like adding 3 lines of code and everything went fine. – gd1 Mar 24 '11 at 20:34
  • This suggestion doesn’t sound that difficult, and as though it ought to work, and is what I was looking for (though it took me several attempts to find it, perhaps because the Q was insufficiently tagged). I actually want to get a test-logging function in C to write to a log open in a C# test-driver, so _gd1_’s approach does not work — incidentally I find it _less_ elegant but more reliably simple, in his situation. Before I found this, I split off a C function yielding the text in an `malloc`ed string; I often find myself undecided whether to code such a formatter or write straight to a file! – PJTraill Feb 25 '16 at 14:43