【问题标题】:Passing output from C++ to PHP将输出从 C++ 传递到 PHP
【发布时间】:2013-02-26 18:49:08
【问题描述】:

我正在创建一个 PHP 文件来将值传递给 c++ .exe,然后它将计算输出并返回该输出。但是,我似乎无法将 .exe 的输出返回到 PHP 文件中。

PHP 代码:

$path = 'C:enter code here\Users\sumit.exe';
$handle = popen($path,'w');
$write = fwrite($handle,"37");
pclose($handle);

C++ 代码:

#include "stdafx.h"
#include <iostream>
using namespace std;

// Declaation of Input Variables:
int main()
{
int num;
cin>> num;

std::cout<<num+5;
return 0;
}

【问题讨论】:

    标签: php c++ integration output


    【解决方案1】:

    我既不建议system 也不建议popen,而是建议proc_open 命令:php.net

    这样称呼

    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
       1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
       2 => array("pipe", "w")   // stderr, also a pipe the child will write to
    );
    proc_open('C:enter code here\Users\sumit.exe', $descriptorspec, $pipes);
    

    之后,$pipes 将填充句柄以将数据发送到程序 ([0]) 并从程序 ([1]) 接收数据。您还将拥有[2],您可以使用它从程序中获取stderr(或者如果您不使用stderr,则直接关闭)。

    不要忘记使用proc_close() 关闭进程句柄和使用fclose() 关闭管道句柄。请注意,在您关闭 $pipes[0] 句柄或写入一些空白字符之前,您的程序不会知道输出是否完整。我建议关闭管道。

    system()popen() 中使用命令行参数是有效的,但如果您打算发送大量数据和/或原始数据,则会遇到命令行长度限制和转义特殊字符的问题。

    【讨论】:

      【解决方案2】:

      在您的 C++ 代码中,我没有看到任何需要传递变量的东西

       int main(int argc, char* argv[])
      

      而不是

       int main()
      

      请记住 argc 是变量的计数,它包括文件的路径,因此您的参数从 1 开始,每个 argv 都是该参数的 c 字符串。如果你需要一个小数,atof 是你的朋友,或者 atoi 是一个整数。

      那么你正在使用popen。 The PHP documentation 表示只能用于阅读或书写。它不是双向的。您想使用proc_open 来获得双向支持。

      无论如何,这就是我编写 C++ 代码的方式:

      #include "stdafx.h"
      #include <iostream>
      
      // Declaation of Input Variables:
      int main(int arc, char* argv[])
      {
         int num;
         num = atoi(argv[1]);
      
         std::cout<<num+5;
         return 0;
       }
      

      注意:我删除了using namespace std,因为我注意到您仍在尝试在主函数中使用命名空间(即std::cout),最好将其排除在全局命名空间之外。

      【讨论】:

        【解决方案3】:

        你正在写入 exe 文件,你应该像

        一样传递你的参数
        system("C:enter code here\Users\sumit.exe 37");
        

        【讨论】:

        • 您还需要更改示例中 main() 的定义。 int main(int argc, char **argv) 或 int main(int argc, char *argv[])
        猜你喜欢
        • 2010-11-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多