问题
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.
回答1:
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);
回答2:
In general, you are doing it the wrong way. This function was meant for C/C++ native console-based applications. In C# you have the System.Diagnostic namespace, and you can easily start new processes with it. Please look here: C++ "system()" in C#
Of course you can use that function, too. The exception is probably called because the DllImport phrase is incomplete, see in .Net 4: PInvokeStackImbalance Exception This thread is about strlen, but I'm almost sure that the system() and strlen() use the same stack convention.
来源:https://stackoverflow.com/questions/11968154/pinvokestackimbalance-while-using-static-extern-int-systemstring-str