我想要的是构建一个 *.so ,然后将其作为 PHP 扩展模块并通过 PHP 调用 *.so 中的函数。
我的步骤如下:
linux下搭建C库,首先创建hello.c
int hello_add(int a, int b) { return a+b; }
然后构建如下:
gcc -O -c -fPIC -o hello.o hello.c
gcc -shared -o libhello.so hello.o
下载php 5.2.17源代码
tar -zxvf php.5.2.17.tar.gz
cd php.5.2.17
./configure ./configure --prefix=/home/user1/php-5.2.17
制作并安装
光盘分机;
./ext_skel --extname=你好
你好
通过删除第 16-18 行中的 dnl 来编辑 config.m4,然后保存并退出。
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])
执行命令:/home/user1/php-5.2.17/bin/phpize
打开 php_hello.h,添加
PHP_FUNCTION(hello_add);
打开 hello.c 更改为:
zend_function_entry hello_functions[] = { PHP_FE(confirm_hello_compiled, NULL) /* For testing, remove later. */ PHP_FE(hello_add, NULL) /* For testing, remove later. */ {NULL, NULL, NULL} /* Must be the last line in hello_functions[] */ };
在文件末尾添加
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); }
./configure --with-php-config=/home/usr1/php-5.2.17/bin/php-config
make LDFLAGS=-lhello
然后 hello.so 在 /home/usre/php-5.2.17/ext/hello/modules 下生成,但使用
nm hello.so
它会打印:`U hello_add 0000000000000a98 T _init`
创建一个php文件进行测试:
<?php if(!dl('btest.so')) { echo "can not load hello.so"; } else { echo "load is done"; echo hello_add(3,4);// here it will throw error in the log } ?>
在日志中,它抱怨:[28-Sep-2014 18:38:28] PHP Fatal error: Call to undefined function hello_add() ....
顺便说一句,我将 hello.so 复制到另一个 LAMP 环境中,而不是使用刚刚构建的 PHP。两个版本都是 5.2.17。
有人能指出发生了什么吗?