2013-03-11 97 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()

使用命令行參數是有效的,但如果你打算髮送大量的數據和/或原始數據,你將不得不使用命令行長度的限制,並逃避特殊字符的麻煩。