在大型公司会有C++程序员和C程序员,他们会做成C库,那我们怎么接入PHP
先确定在linux是否能运行该库
对方给了so库,先不急着集成到PHP,先让linux能跑通
模仿如下进行验证运行
/**
* hello.c
* To compile, use following commands:
* gcc -O -c -fPIC -o hello.o hello.c
* gcc -shared -o libhello.so hello.o
*/
int hello_add(int a, int b)
{
return a + b;
}
然后将它编译成.so文件并放到系统中:
$ gcc -O -c -fPIC -o hello.o hello.c
$ gcc -shared -o libhello.so hello.o
$ su
# echo /usr/local/lib > /etc/ld.so.conf.d/local.conf
# cp libhello.so /usr/local/lib
# /sbin/ldconfig
写段小程序来验证其正确性:
/**
* hellotest.c
* To compile, use following commands:
* gcc -o hellotest -lhello hellotest.c
*/
#include <stdio.h>
int main()
{
int a = 3, b = 4;
printf("%d + %d = %d\n", a, b, hello_add(a,b));
return 0;
}
编译并执行:
$ gcc -o hellotest -lhello hellotest.c 这条有误提示找不到
$ ./hellotest
3 + 4 = 7
上述核心步骤在于 将so库存入系统,关键代码如下
# echo /usr/local/lib > /etc/ld.so.conf.d/local.conf
# cp libhello.so /usr/local/lib
# /sbin/ldconfig
进入php安装文件的ext
通过命令建立一个名为 hello 的模块
./ext_skel --extname=hello
进入文件
cd hello
编辑 config.m4 文件
去掉第16行和第18行的注释
16: PHP_ARG_ENABLE(hello, whether to enable hello support,
17: dnl Make sure that the comment is aligned:
18: [ --enable-hello Enable hello support])
执行
然后执行 phpize 程序,生成configure脚本:
phpize
编写 hello.c
在hello.c找到const zend_function_entry zhd_test_functions,声明一个函数:PHP_FE(hello_add, NULL)
const zend_function_entry zhd_test_functions[] = {
PHP_FE(confirm_zhd_test_compiled, NULL) /* For testing, remove later. */
PHP_FE(hello_add, NULL)
PHP_FE_END /* Must be the last line in zhd_test_functions[] */
};
具体实现该函数
在申明代码上面实现
PHP_FUNCTION(hello_add)
{
第三方so的函数执行
}
保存退出,编译并安装:
./configure
make LDFLAGS=-lhello #注意libhello.so lib和so之间
放到php拓展内
cp modules/zhd_test.so /usr/local/php/lib/php/extensions/no-debug-non-zts-20160303/
重启php
lnmp restart
php调用
hello_add()
查阅文件:
https://cn.charlee.li/use-local-so-in-php.html
https://blog.csdn.net/b1303110335/article/details/77864786
glibc版本过低报错
https://www.cnblogs.com/dpf-learn/p/8763696.html