Search code examples
c#msvcrt

PInvokeStackImbalance while using "static extern int system(string str)"


I'm trying to use the system(string str) Command for dos-operations in C#.

namespace XYZ
{
    internal class Program
    {
        [DllImport("msvcrt.dll")]
        static extern int system(string str);

        static void Main(string[] args)
        {
             string Command = Console.ReadLine();
             system(Command); 
             /* Excutes command, then "PInvokeStackImbalance". */
        }
    }
}

I know using static extern int system(string str) is a bad solution, but I've tried other solutions which did not work.


Solution

  • You forgot to specify the calling convention:

    [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern int system(string str);
    

    I normally try to explain why but that seems unnecessary here ;) This is otherwise unlikely to fix your problem, whatever it may be, it is the same thing as

    Process.Start("cmd.exe", "/c " + str);