Why is the development of the php extension very different from the development of C ++?

I have been a PHP developer for quite some time, and I'm starting to use some of the limitations in the language. So, with that said, I decided that the next step in my development cycle would be to switch to C ++ and create some extensions!

As I went through some standard “Hello World” tutorials, everything seems to make sense for the most part. I built a pretty decent tic-tac-toe application, so I decided it was time to start diving into PECL and see how it works. What I found, however, is poisoning my mind.

Could someone explain both the purpose and the reasoning for some reason like this:

PHP_FUNCTION(helloWorld) { RETURN_STRING("Hello World"); } 

no more line by line:

 string helloWorld() { return "Hello World" } PHP_REGISTER_METHOD("helloWorld"); 

I don't pretend to know more than the people who created this language, and I'm not trying to worry. It seems (at least from a beginner's point of view) that creating a PHP extension is not like creating a C ++ program. This is a completely different language completely, except for some basic syntax rules.

Any help would be greatly appreciated. Just a beginner trying to grow :)

+4
source share
1 answer

The extension of PHP extensions is not much different from other C / C ++ developments. The only thing that is especially important is that you need to connect the world of PHP scripts with your C / C ++ functions. This task is not trivial, and weird macros like PHP_FUNCTION are needed here.

For example, if you want to call the "helloWorld" function from PHP, the interpreter needs to look for "helloWorld" and map it to function C. This function must have a specific signature, which means that it must take a certain set of parameters and must return a certain value. This is not arbitrary, and the interpreter cannot simply call any C / C ++ function.

This is how low-level languages ​​such as C work, you cannot "check" what arguments the function performs.

In particular, all values ​​in the PHP interpreter are special structures that cannot be converted to C ++ types. PHP string is different from C ++ std :: string. The PHP API provides all sorts of tools for converting values, but you need to know how to use them.

Once you know how to write a C function that can be called with PHP, you are in the “C / C ++ world”, where you can call another C / C ++ function and use C / C ++ types. Hence, just like writing clean C / C ++ applications. Well, until you have to return values ​​back to the world of PHP, where again you have to use the PHP API tools.

There are tools that can make your life easier by helping to generate the required “glue code” for an interface with a scripting language such as PHP and “clean” C ++ projects. Check out SWIG , which is probably the clearest example.

+6
source

Source: https://habr.com/ru/post/1403686/


All Articles