Search code examples
c#pinvoke

PInvoking stdin, stdout and stderr to unmanaged dll


I have a C header file that contains something like this:

void init(FILE* in, FILE* out, FILE* err);

I'm guessing this equates to the following PInvoke signature:

[DllImportAttribute("mylib", EntryPoint = "init")]
public static extern void init(IntPtr @in, IntPtr @out, IntPtr err);

Incidentally, I want to invoke this method. Can I get the IntPtr from Console.In, Console.Out, Console.Error somehow?

It should work on Linux and Windows, and not Windows exclusively.


Solution

  • You can use GetStdHandle to obtain handles to the standart input(STD_INPUT_HANDLE), output(STD_OUTPUT_HANDLE) and error(STD_ERROR_HANDLE) file.

    You can then write and read from those files using WriteFile, ReadFile functions.

    After that, if you still need a FILE structure, follow these steps to create one.

    How make FILE* from HANDLE in WinApi?