Let PHP can call C function -FFI expansion

Let PHP can call C function -FFI expansion

In large companies, there are generally many programming languages. For example, let Java make the microserignment layer, with C ++ for the underlying operation, use PHP to do the intermediate layer, and finally use JS display effect. Most of these languages ​​are completed by RPC, or directly using different languages ​​to use different languages. So, can our PHP code call these languages ​​directly? In fact, PHP really prepared a expansion library that can directly call the C language, and this extension is still built by default in PHP, it is FFI extension.

What is FFI

FFI, Foreign Function Interface, external function interface. This extension allows us to load some public libraries (.dll ,.so), in fact, can call some of the data structure and functions of C. It is already an extension released with the PHP source code. You can add -with-ffi to PHP programs when compiling.

We are already compiled well, so we can find this extension directly, and you can install the simple extension installation steps.

cd php-7.4.4/ext/ffi/
phpize
./configure
make && make install

Remember to open the extension in the php.ini file after the installation is complete. About this extension requires note, it has a configuration item for ffi.enable, by default, the value of this configuration item is "preload", which enables FFI only in the CLI SAPI environment. Of course, we can also modify it to "True" or "false" to turn it on and off. Set to "True" will enable this extension to be enabled in any environment.

Use FFI to call C function

Next, let's take a look at how it calls a function of C.

// Create a FFI object, load libc and import the Printf function
$ffi_printf = FFI::cdef(
 "INT Printf (const char * format, ...);", // C definition rules
 "Libc.so.6"); // Specify the libc library
 // Call the PRINTF function
$ffi_printf->printf("Hello %s!\n", "world"); // Hello World

 / / Load MATH and import a POW function
$ffi_pow = FFI::cdef(
    "double pow(double x, double y);", 
    "libboost_math_c99.so.1.66.0");
 // This is called a POW function, not PHP yourself.
echo $ffi_pow->pow(2,3), PHP_EOL; // 8

We created two objects, called C's printf () and POW () functions. FFI :: CDEF () is used to create an FFI object that receives two parameters, one is a string containing regular C language (type, structure, function, variable, etc.) declaration sequence. In fact, this string can be pasted from the C header file. The other parameter is to load and define the name of the shared library file for the link. That is, what we need .dll or .so file, it is corresponding to our declaration string, such as the calculation function of POW () in libc.so.6, so we will find Math-related C. Language calculation function library.

Define variables and arrays

Of course, FFI can also define variables and arrays.

// Create an INT variable
$x = FFI::new("int");
var_dump($x->cdata); // int(0)

 / / Assignment for variables
$x->cdata = 5;
var_dump($x->cdata); // int(5)

 // Computational variable
$x->cdata += 2;
var_dump($x->cdata); // int(7)


 // Combine the above two FFI object operations

echo "pow value:", $ffi_pow->pow($x->cdata, 3), PHP_EOL;
// pow value:343
$ffi_printf->printf("Int Pow value is : %f\n", $ffi_pow->pow($x->cdata, 3));
// Int Pow value is : 343.000000


 // Create an array
$a = FFI::new("long[1024]");
 / / Assignment for array
for ($i = 0; $i < count($a); $i++) {
    $a[$i] = $i;
}
var_dump($a[25]); // int(25)

$sum = 0;
foreach ($a as $n) {
    $sum += $n;
}
var_dump($sum); // int(523776)

 VAR_DUMP (count ($ a)); // int (1024) array length
 VAR_DUMP (FFI :: SizeOf ($ a)); // int (8192), memory size

Use the ffi :: new () function to create a C's data structure, that is, the variable declaration, the content of these variables will be saved in the CDATA property. The array can operate the return value of this function. Of course, when we want to end the use, you still need to use ffi :: free () to release variables, just like the development of C language.

to sum up

Does it feel very high? But please pay attention, the C function called FFI call does not have the efficiency of the PHP itself. For example, this POW () function, which is more efficient to use PHP. Moreover, although the FFI extension is already an extension that follows PHP synchronous release, it is still experimentally. That is, this extension is prepared for other functions that can be used in the future, and there are still many uncertainties. So if you need a similar function in the production environment, then you should do more in-depth research.

Test code: https://github.com/zhangyue0503/dev-blog/blob/master/php/202004/source/%e8%AE%A9PHP%E8%83%BD%E5%A4%9F%E8%B0% 83% E7% 94% A8C% E7% 9A% 84% E5% 87% BD% E6% 95% B0-FFI% E6% 89% A9% E5% B1% 95.php

Reference document: https://www.php.Net/manual/en/intro.ffi.phphttps://www.php.net/manual/en pffi.examples-basic.php

Intelligent Recommendation

[C ++ 11] can call object wrapper function

Calling object wrapper Std :: function is a wrapper that can call an object. It is a class template that can accommodate all callable objects other than class members (functions) pointers. By specifyi...

03, FLUTTER FFI function

  FLUTTER FFI Learning Notes "Flutter FFI Summary" "Flutter FFI Basic Data Type" "Flutter FFI function" "FLUTTER FFI string" FLUTTER FFI Structures Flutter...

Print_backtrace() function, c/c++ can also print function call stack

Envy java can easily print the function stack, can c / c + + achieve? The bt command of gdb can see the call stack of the function. Sometimes it is helpful to directly print the function call stack fo...

var, let, const, arrow function, string related expansion, function expansion

var exists pre-parsed let does not exist pre-parsed Variables declared by let are not allowed to be repeated (in the same scope) ES6 introduces block-level scope. Variables defined in the block are no...

Nodejs call DLL via FFI

The first step is to establish a DLL, provide the method as follows Second step to install FFI (premise installed python2.x environment) npm install --save ffi The third step creates a test file Refer...

More Recommendation

[Nodejs] NodeJS FFI call DLL

NodeJS FFI call DLL...

JS call so via FFI

1. Install FFI (dependent GCC environment) Project open source address:GitHub - node-ffi/node-ffi: Node.js Foreign Function Interface 1. Installation: NPM Install Node-GYP 2. Installation: NPM Install...

C Language: Can a C file call a function in another C file?

Premise:A.c function has a main () function, and calls the B_Fun () function in B.C. Demo results: Code display:  ...

nodejs uses the ffi library to call the user32 library function of the windows system to obtain the size of the desktop program window

The ffi library is a dependent library for operating windows system library functions provided by npm. The installation process will be troublesome and requires compilation. You may need to install wi...

nodejs uses the ffi library to call the user32 function of the windows system to simulate user login operations

As shown in the question, for general desktop programs, user login is very simple, that is, find the user name and password input box, enter the corresponding user name and password, and then click th...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top