2013-03-11 39 views
1

我正在创建一个PHP文件以将值传递给C++ .exe,然后它将计算输出并返回该输出。但是,我似乎无法将.exe的输出返回到PHP文件中。将输出从C++传递到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; 
} 

回答

0

在你的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)和最好让它远离全局命名空间。

+0

谢谢,这个工作很完美。 – Wayne 2013-03-11 17:08:10

0

你正在编写成exe文件,你应该通过你的论点一样

system("C:enter code here\Users\sumit.exe 37"); 
+0

您还需要更改样本中main()的定义。 int main(int argc,char ** argv)或int main(int argc,char * argv []) – Beachwalker 2013-03-11 14:42:59

2

我建议既不system也不popenproc_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()

使用命令行参数是有效的,但如果你打算发送大量的数据和/或原始数据,你将不得不使用命令行长度的限制,并逃避特殊字符的麻烦。