プログラミング

PHPとC言語の連携

PHPとC言語との連携は非常に簡便に実現できました。但し,PHPのFFIもジュールはバージョン7.4以降のものにしか対応していないようなので,古いPHPでは実行できないかもしれません。

#!/bin/bash
gcc --shared -fPIC -o libadd.so -xc - << EOS
int add(int x, int y) { return x + y; }
EOS

cat << EOF > php2c.php
<?php
  \$ffi = FFI::cdef("int add(int, int);", "libadd.so");
  print("30 + 40 = " . \$ffi->add(30, 40) . "\n");
?>
EOF

php80 php2c.php