Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PHP and C++ pass data between each other?

Tags:

c++

php

I have a lot of mathematical calculations in my PHP script, which can be quite slow at times. I'm wondering if it's possible to pass data from PHP to C++, do the calculations in C++, then pass the results back to PHP?

P.S. I'm not very good at C++.

like image 583
Leo Jiang Avatar asked Mar 30 '12 02:03

Leo Jiang


People also ask

Can you use C with PHP?

PHP will not run your C code, even though they have similar syntaxes. The PHP exec function will execute a command similar to how it is done in a shell or command prompt.


1 Answers

You can write a PHP module, which is a piece of C code that exposes a new built-in function to the PHP interpreter. This will be much faster than spinning up a second process via exec().

However, such modules are difficult to write, the build tools are clumsy, and passing parameters back and forth between PHP and C requires great care around memory allocation and reference counting. Also, C is not C++, so you will need an extern C layer around your C++ code to export functions to PHP. (Or else write your extension in C instead of C++.)

So unless your speed requirement is really severe, it will be easier to use exec or proc_open and pass data back and forth through file pointers. This would be just like writing a C++ program that reads from standard input and emits to standard output.

like image 67
Crashworks Avatar answered Sep 22 '22 09:09

Crashworks