2017-06-15 66 views
1

我想沟通PHP和C++代码。PHP和C++之间的通信

我需要在它们之间传递一个大的JSON。 问题是我目前使用“passthru”,但由于某些原因,我不知道,C++代码没有收到整个参数,但在JSON为3156时被剪切为528个字符。

通过执行测试,我能够验证“passthru”命令支持的字符数与3156一样多。但我不知道C++中是否有最大输入参数大小。

PHP应用程序如下:

passthru('programc++.exe '.$bigJSON, $returnVal); 

的C++应用程序:

int main(int argc, char* argv[]){ 
    char *json = argv[1]; 
} 

有没有什么办法来解决这个问题?我已经阅读了PHP扩展和IPC协议,但问题是我必须做一个多平台程序(我必须有一个版本的Windows,另一个Linux和Mac)。我认为使用PHP扩展和IPC协议(据我所知)使事情复杂化了很多。

+2

是'$ bigJSON' [逃脱](http://php.net/manual/en/function.escapeshellarg.php)是否正确?如果它包含字符528附近的未转义空格,它可能成为C++应用程序的第二个参数。 – rickdenhaan

+2

而不是将它作为参数传递我会使用[proc-open](http://php.net/manual/en/function.proc-open.php)输入输出流 –

+0

我尝试使用“escapeshellarg”,问题是,在Windows中,“espaceshellarg”从JSON中删除双引号。而且C++中的JSON解释器需要它们=( –

回答

0

解决方案: 解决方法是使用“proc_open”并使用管道stdin和stdout。就我而言,我使用库rapidjson。我在PHP中添加双引号以便快速处理JSON并处理JSON。 PHP:

$exe_command = 'program.exe'; 

$descriptorspec = array(
    0 => array("pipe", "r"), // stdin 
    1 => array("pipe", "w"), // stdout -> we use this 
    2 => array("pipe", "w") // stderr 
); 

$process = proc_open($exe_command, $descriptorspec, $pipes); 
$returnValue = null; 
if (is_resource($process)){ 
    fwrite($pipes[0], $bigJSON); 
    fclose($pipes[0]); 

    $returnValue = stream_get_contents($pipes[1]); 
    fclose($pipes[1]); 
} 

C++:

int main(int argc, char* argv[]){ 
    std::string json; 
    std::getline (std::cin, json); 
    cout << json << endl; // The JSON 
}