ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] > [参考](http://www.bkjia.com/Linux/964805.html) ## 创建一个 .so 文件 ## 1. 创建`hello.c` ``` int hello_add(int a, int b) { return a + b; } ``` ## 2. 编译 ``` $ 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 ``` ## 3. 验证是否正确加载 创建 `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 # -lhello 编译时加入动态so 文件 $ ./hellotest 3 + 4 = 7 ``` > 在 CentOS 下可以正常编译 ## 4. 下载php 源码 进入`ext` ``` $ ./ext_skel --extname=hello $ cd hello ``` ## 5. 修改 `config.m4` `去掉第16行和第18行的注释(注释符号为 dnl )` ``` 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 ``` ## 6. 修改` php_hello.h` 在文件后尾添加 ``` PHP_FUNCTION(hello_add); ``` ## 7. 编辑`hello.c` ``` zend_function_entry hello_functions[] = { PHP_FE(confirm_hello_compiled, NULL) /* For testing, remove later. */ PHP_FE(hello_add, NULL) /* 此处添加要实现的方法 */ {NULL, NULL, NULL} /* Must be the last line in hello_functions[] */ }; //文末,添加具体实现 PHP_FUNCTION(hello_add) { longint a, b; longint result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &a, &b) == FAILURE) { return; } result = hello_add(a, b); RETURN_LONG(result); } ``` ## 8. 编译安装 ``` $ phpize $ ./configure --with-php-config=/www/server/php/56/bin/php-config $ make clean # 清除编译 $ make LDFLAGS=-lhello #-lhello 表示加载 动态库 libhello.so 文件 $ sudo make install ``` 在`php.ini`加入`extension=hello.so` ## 9. 测试 `php -r"echo hello_add(3, 4);"` //输出7 或者使用`php hello.php`