Passing data from C++ to PHP

我们两清 提交于 2019-12-05 14:49:54
Paul Dixon

You could have your c++ app send its output to stdout, then call it from PHP with backticks, e.g.

$output=`myapp $myinputparams`;

wow thanks a lot to Columbo & Paul Dixon.

Now I can run php to call c++ thn pass back value to php~ =)

Here I provide a sample cpp & php for it:

A simple program for adding up inputs:

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:

<?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

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. 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. for your C++ program.

This article about wrapping C++ classes in a PHP extension may help.

EDIT: all the solutions in other answers are far simpler, but less flexible. It all depends on what you need.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!