LINUX下PHP生成并调用C的.so文件
1,安装PHP环境到/usr/local/php
2,进入源码包cd /usr/local/php-5.5.3
3,建立要生成的.so文件的扩展骨架
cd /usr/local/php-5.5.3
./ext_skel --extname=test
test就是你要生成的.so的名字,例如test.so
4,修改配置文件/test/config.m4
取消下面两行的dnl注释,即去掉dnl
PHP_ARG_ENABLE(test, whether to enable test support,dnl Make sure that the comment is aligned:[ --enable-test Enable test support])
如果说使用C++ 进行编译,那么要将test.c改为test.cpp,并在/test/config.m4中加入一下(如果不是C++,则不需要)
PHP_REQUIRE_CXX() PHP_ADD_LIBRARY(stdc++, 1, EXTRA_LDFLAGS)PHP_NEW_EXTENSION(test, test.cpp, $ext_shared)
5,修改php_test.h中的代码,加入自定义函数的声明
PHP_MINIT_FUNCTION(test);PHP_MSHUTDOWN_FUNCTION(test);PHP_RINIT_FUNCTION(test);PHP_RSHUTDOWN_FUNCTION(test);PHP_MINFO_FUNCTION(test);PHP_FUNCTION(confirm_test_compiled); /* For testing, remove later. */PHP_FUNCTION(testFunc);
6,在test.c(test.cpp)中加入自定义函数代码:
(1)在该位置引入用到的头文件
#ifdef HAVE_CONFIG_H#include "config.h"#endif#include <stdio.h>#include <string.h>#include <math.h>
#include "php.h"#include "php_ini.h"#include "ext/standard/info.h"#include "php_test.h"
(2)在该位置加入函数入口
const zend_function_entry test_functions[] = { PHP_FE(confirm_test_compiled, NULL) /* For testing, remove later. */ PHP_FE(testFunc, NULL) PHP_FE_END /* Must be the last line in test_functions[] */};
(3)在文件尾部添加函数代码,也可以在这里定义其他函数
PHP_FUNCTION(testFunc) { char *x = NULL; char *y = NULL; int argc = ZEND_NUM_ARGS(); int x_len; int y_len; if (zend_parse_parameters(argc TSRMLS_CC, "ss", &x, &x_len, &y, &y_len) == FAILURE) return; int result_length = x_len + y_len; char* result = (char *) emalloc(result_length + 1); strcpy(result, x); strcat(result, y); RETURN_STRINGL(result, result_length, 0); }
7,建立扩展模块,直接输入以下
/usr/local/php/bin/phpize
(/usr/local/php是php的安装路径,这个要看你安在哪了,但建议软件都安装在/usr/local下)
8,如下
./configure --with-php-config=/usr/local/php/bin/php-config (/usr/local/php/bin/php-config是你安装的php的路径)
make
make install
说明一下,如果make出错,改好后继续make;如果make install 出错,需要执行make clean 和/usr/local/php/bin/phpize --clean
9,查看test.so是否生成
make insall成功后会给出路径
一般放在:/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/test.so
*************************************************以上就生成.so文件了***********************分割线********************************************************************************************************
下面讲解如何调用
很简单
修改php.ini文件
/usr/local/lib/php.ini(这个路径都不大相同,具体要看你放在哪了,如果找不到,那么去根目录下执行这条指令find -name php.ini)
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/"
extension = "teste.so"
之后重启php或者apache即可
**********************************************以上内容就完成了**********************************************分割线************************************************************************************************************************
下面补充一个过程中可能会出现的错误:autoconf有关的错误
解决如下:
yum list autoconf*
之后会列出几个版本,选择最高版本的安装,比如说2.59
yum install autoconf259
成功之后需要配置环境变量:
export PHP_AUTOCONF=/usr/bin/autoconf-2.59
export PHP_AUTOHEADER=/usr/bin/autoheader-2.59
完!