2

I've got a vaguely Java background and just installed Visual Studio Community 2015. Playing about with it so have a console app up and running and wanted to use above function after attaching to a different Console. Trouble is I have no idea about the appropriate declaration for this function - can someone tell me what it should be in this instance but also a good pointer for me in future so I can work it out on my own. The IDE doesn't seem to help much

using System.Runtime.InteropServices;

namespace ConsoleStuff
{
    class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool GetConsoleHistoryInfo();

        static void Main(string[] args)
        {
                    GetConsoleHistoryInfo(); // <-- PInvokeStackImbalance occurred
        }
    }
}
user1561108
  • 2,666
  • 9
  • 44
  • 69

1 Answers1

1

You should declare it like this:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetConsoleHistoryInfo(ref CONSOLE_HISTORY_INFO ConsoleHistoryInfo);

You will need the CONSOLE_HISTORY_INFO type too for this to work:

[StructLayout(LayoutKind.Sequential)]
public struct CONSOLE_HISTORY_INFO
{
    uint cbSize;
    uint HistoryBufferSize;
    uint NumberOfHistoryBuffers;
    uint dwFlags;
} 

A lot of useful PInvoke information can be found at PInvoke.net. You should however double check it against the MSDN to see if it fits.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • thanks - where is the best resource to get such info? – user1561108 Jun 21 '15 at 19:09
  • 1
    [pinvoke.net](http://www.pinvoke.net) is the crappiest resource for P/Invoke there is. Period. It is stock full of wrong, and this structure declaration is no exception: The native data type `UINT` is 32 bits, and does **not** map to C#'s `ushort` (16 bits). See [Marshaling Data with Platform Invoke](https://msdn.microsoft.com/en-us/library/fzhhdwae.aspx) for a reliable reference. – IInspectable Jun 21 '15 at 19:17
  • @IInspectable hm, seems you are right. That's strange, it was pretty reliable once. – nvoigt Jun 21 '15 at 19:21
  • No. It has **not ever been reliable**. Not at any point in time, not in this universe. To this date you can be pretty confident, that the majority of declarations is not ready for 64-bit platforms. – IInspectable Jun 21 '15 at 19:23
  • 2
    The parameter should be `ref` rather than `out`. Since `cbSize` is passed in to the function. Use MSDN and the headers to get the C++ declarations, and translate them. – David Heffernan Jun 21 '15 at 19:37