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++.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With