php调用C已编译的so库文件

本文介绍在Linux环境下将so库集成到PHP的步骤。先验证Linux能否运行该库,将so库存入系统;接着进入PHP安装文件的ext,创建模块、编辑config.m4文件、执行phpize程序;编写并实现hello.c文件,编译安装后放入PHP拓展内,重启PHP即可调用,还给出相关查阅文件链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先确定在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.youkuaiyun.com/b1303110335/article/details/77864786
glibc版本过低报错
https://www.cnblogs.com/dpf-learn/p/8763696.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值