[英]Passing data from C++ to PHP
I need to pass a value from PHP to C++. 我需要将值从PHP传递给C ++。 I think I can do with PHP's passthru()
function. 我想我可以使用PHP的passthru()
函数。 Then I want C++ to do something to that value and return the result to PHP. 然后我希望C ++对该值执行某些操作并将结果返回给PHP。 This is the bit I can't work out, does anyone know how to pass data from C++ to PHP? 这是我无法解决的问题,有谁知道如何将数据从C ++传递到PHP? I'd rather not use an intermediate file as I am thinking this will slow things down. 我宁愿不使用中间文件,因为我认为这会减慢速度。
您可以让您的c ++应用程序将其输出发送到stdout,然后使用反引号从PHP调用它,例如
$output=`myapp $myinputparams`;
wow thanks a lot to Columbo & Paul Dixon. 哇非常感谢Columbo和Paul Dixon。
Now I can run php to call c++ thn pass back value to php~ =) 现在我可以运行php来调用c ++ thn传回值到php~ =)
Here I provide a sample cpp & php for it: 在这里,我提供了一个示例cpp和php:
A simple program for adding up inputs: 一个简单的程序,用于添加输入:
a.cpp (a.exe): a.cpp(a.exe):
#include<iostream>
#include<cstdlib>
using namespace std;
int main(int argc, char* argv[]) {
int val[2];
for(int i = 1; i < argc; i++) { // retrieve the value from php
val[i-1] = atoi(argv[i]);
}
int total = val[0] + val[1]; // sum up
cout << total; // std::cout will output to php
return 0;
}
sample.php: sample.php:
<?php
$a = 2;
$b = 3;
$c_output=`a.exe $a $b`; // pass in the two value to the c++ prog
echo "<pre>$c_output</pre>"; //received the sum
echo "Output: " . ($output + 1); //modify the value in php and output
?>
output: 输出:
5
Output: 6
This article about wrapping C++ classes in a PHP extension may help. 这篇关于在PHP扩展中包装C ++类的文章可能有所帮助。
EDIT: all the solutions in other answers are far simpler, but less flexible. 编辑:其他答案中的所有解决方案都简单得多,但灵活性较差。 It all depends on what you need. 这一切都取决于你需要什么。
If you need to communicate to a running C++ program, a socket connection over the localhost might be the simplest, most platform-independent and most widely supported solution for communicating between the two processes. 如果需要与正在运行的C ++程序进行通信,则localhost上的套接字连接可能是最简单,最独立于平台且最广泛支持的两个进程之间通信的解决方案。 Sockets were traditionally built to communicate over network interfaces, but I have seen them used in many cases as a method of doing a pipe. 传统上,套接字构建为通过网络接口进行通信,但我已经看到它们在很多情况下用作管道的方法。 They are fairly ubiquitous and supported in most modern languages. 它们无处不在,并且在大多数现代语言中得到支持。
Here's a C guide for socket programming. 这是套接字编程的C指南。 for your C++ program. 为您的C ++程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.