【问题标题】:PInvokeStackImbalance while using "static extern int system(string str)"使用“静态外部 int 系统(字符串 str)”时的 PInvokeStackImbalance
【发布时间】:2014-07-16 21:54:21
【问题描述】:

我正在尝试在 C# 中使用 system(string str) 命令进行 dos 操作。

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". */
        }
    }
}

我知道使用static extern int system(string str) 是一个糟糕的解决方案,但我尝试了其他不起作用的解决方案。

【问题讨论】:

    标签: c# msvcrt


    【解决方案1】:

    一般来说,你做错了。此函数适用于基于 C/C++ 本地控制台的应用程序。在 C# 中,您拥有 System.Diagnostic 命名空间,您可以使用它轻松启动新进程。请看这里:C++ "system()" in C#

    当然,您也可以使用该功能。可能调用异常是因为 DllImport 短语不完整,请参阅in .Net 4: PInvokeStackImbalance Exception 这个线程是关于 strlen,但我几乎可以肯定 system() 和 strlen() 使用相同的堆栈约定。

    【讨论】:

      【解决方案2】:

      您忘记指定调用约定:

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

      我通常会尝试解释原因,但在这里似乎没有必要;)否则这不太可能解决您的问题,不管它是什么,它与

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 2011-01-06
        • 2013-07-16
        • 2015-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多