PInvokeStackImbalance while using “static extern int system(string str)”

情到浓时终转凉″ 提交于 2019-12-02 09:10:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!