Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking PHP with local C++ program

I've been looking into this for several hours, but everything I've looked at seems rather daunting. I've been using PHP for all of the simple stuff on my website so far. I'm doing a lot of statistical work, and I would like to have c++ available for the more intense calculations.

The c++ would be running locally on the same Unix machine as PHP.

Something like the following is what I'm at a loss for how to do:

<?php 
//c++ program has a counter initialized to 0
//PHP tells c++ to add 5 to the counter.  $incremented is 5
$incremented = increment_in_cpp_and_return(5);
//$incremented_again will be 7
$incremented_again = increment_in_cpp_and_return(2);
?>

Of course, I'm running some monte-carlo simulations and traversing really big trees instead of incrementing numbers, but that's not what's holding me back.

C++ just needs to listen for a number and return another number (maybe some stuff in JSON at most). It is important for the c++ to keep track of its variables between calls.

I've done a lot of reading on TCP, socket programming, etc and I'm just a little doubtful that this as complicated as the examples make it out to be. A lot of things have pointed me to this https://beej.us/guide/bgnet/html/multi/clientserver.html#simpleserver

If it really is more than 100 lines of c++, are there some popular libraries, or is there a simple implementation in another language?

Thanks!

like image 386
dcc310 Avatar asked Dec 26 '11 20:12

dcc310


1 Answers

If you only want to access your C++ program from PHP (or use PHP as the web frontend for your C++ code), an alternative to communicating over a socket would be to embed the C++ code into PHP as an extension.

There's a fair amount of boilerplate code associated with it, but most of it is generated for you by the ext_skel script (included in the PHP source).

Most information online about writing PHP extensions relates to using C, see Extending PHP with C++? for a couple of gotchas related to using C++ for this.

like image 167
John Carter Avatar answered Oct 05 '22 16:10

John Carter