发新帖

[PHP] [C/VC/C++] php调用C语言生成的so文件

零下一度 2022-2-14 1002

一、创建C动态库,使用gcc命令生成so文件的方法步骤

1、创建hello.c文件,在终端执行命令

vim hello.c

编辑hello.c文件,内容如下

int hello_add(int a, int b)
{
    return a + b;
}

2、生成.o文件,在终端执行命令

 // -fPIC:是指生成的动态库与位置无关  
gcc -O -c -fPIC -o hello.o hello.c

3、生成.so文件,在终端执行命令

// -shared:是指明生成动态链接库 
gcc -shared -o libhello.so hello.o

4、把库地址写入到配置文件中,在终端执行命令

sudo sh -c "echo '/usr/local/lib' >> /private/etc/ld.so.conf.d/local.conf"

5、创建hellotest.c测试文件,在终端执行命令

vim hellotest.c
#include <stdio.h>
#include "hello.c"
int main()
{
int a = 3, b = 4;
printf("%d + %d = %d\n", a, b, hello_add(a, b));
return 0;
}

6、编译测试文件,生成测试程序,在终端执行命令

gcc -o hellotest -lhello hellotest.c

7、运行测试程序,在终端执行命令

./hellotest


二、php调用C语言生成的so文件

1、拷贝自定义libhello.so库

cp libhello.so /usr/local/lib
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH

2、ldconfig 

在这里说明一下,之前的linux系统的用户动态库目录设置好像是在/etc/ld.so.conf.d/local.conf文件中,而在我使用的ubuntu12.04中是在/etc/ld.so.conf.d/libc.conf这个文件中,而且默认已设置为/usr/local/lib这个目录,将我们的so文件放到这个目录后,需用ldconfig命令使其生效。 

# echo /usr/local/lib > /etc/ld.so.conf.d/base.conf
# cp libhello.so /usr/local/lib
gcc -shared -o libhello.so libhello.o

# /sbin/ldconfig

/www/php/71/lib/php/extensions/no-debug-non-zts-20160303

cd php-7.1.33/ext

./ext_skel --extname=hello

cd hello

1、修改php_hello

打开”php_hello.h”,在#endif/* php_hello_H */上一行,加入代码“PHP_FUNCTION(hello_add);”,声明在PHP中可调的函数。

2、修改

打开”hello.c”,找到PHP_FE(confirm_hello_compiled,    NULL) /* For testing, remove l ater. */行,在下面加上PHP_FE(hello_add, NULL)代码如下:

const zend_function_entry hweesdk_functions[] = {
        PHP_FE(confirm_hello_compiled,        NULL)           /* For testing, remove later. */
        PHP_FE(hello_add,        NULL) 
        PHP_FE_END      /* Must be the last line in hello_functions[] */
};

3、还是在”hello.c”中,在上面这段代码的后面加上如下代码,这是PHP中”hello”函数的执行内容,就是调用动态库中的”hello_add”函数。

PHP_FUNCTION(hello_add)
{
    long int a, b;
    long int result; 
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll",&a,&b) == FAILURE) {
        return;
    }
    result = hello_add(a,b);
    RETURN_LONG(result);
}

4、执行

打开”config.m4”,该文件中”dnl”即为注释符号,确保下图中16和18行没有注释。



5、生成Makefile,编译并部署  /www/php/71/bin/phpize

$ ./configure --with-php-config=/www/php/71/bin/php-config
$ make LDFLAGS=-lhello   # 说明连接时需要hello库
$ make install    # 部署时需要sudo

 

 

参考文章:http://www.bjhee.com/php-ext.html

参考文章:https://cloud.tencent.com/developer/article/1804186




最新回复 (0)
返回
零下一度
主题数
928
帖子数
0
注册排名
1