標籤:

php編寫擴展調用動態so庫

c擴展

#vim hello.c#include <stdio.h>int hello(char *name) { printf("hello %s
", name); }#gcc -O -c -fPIC -o hello.o hello.c // -fPIC:是指生成的動態庫與位置無關 #gcc -shared -o libhello.so hello.o // -shared:是指明生成動態鏈接庫 #cp libhello.so /usr/local/lib // 把生成的鏈接庫放到指定的地址 #ldconfig // 用此命令,使剛才寫的配置文件生效

測試so庫

#include <stdio.h> int main() { char *name; name = "Zane"; hello(name); return 0; }#gcc -o hellotest -lhello hellotest.c // 編譯測試文件,生成測試程序 #./hellotest // 運行測試程序

php調用c擴展

#cd php/ext // php/ext 目錄#vim hello.proto //定義原型string hello(string name)#./ext_skel --extname=hello --proto=hello.proto#cd ./hello#vim config.m4 去掉兩行dnl注釋PHP_ARG_ENABLE(hello, whether to enable hello support,dnl Make sure that the comment is aligned:[ --enable-hello Enable hello support])#phpize#./configure --with-php-config=/usr/local/php/bin/php-config#vim Makefile //在LDFLAGS 追加你的庫 libhello.so 就 添加 -lhello#vim hello.c 編寫需要的c語言程序/* {{{ proto string hello(string name) */PHP_FUNCTION(hello){char *name = NULL;int argc = ZEND_NUM_ARGS();size_t name_len;if (zend_parse_parameters(argc, "s", &name, &name_len) == FAILURE) return;hello(name);}/* }}} */#make #./libtool --finish /usr/local/lib/#make install#vim path/php.ini

二選一

1.允許dl()動態載入so擴展功能enable_dl = On

<?php dl("hello.so"); hello(Zane); ?>

2.靜態載入enable_dl = Off 需要添加 extension=hello.so

<?php hello(Zane); ?>

重啟apache、nginx或者任意http伺服器。

參考鏈接

php調用C/C++動態鏈接庫

用C/C++擴展你的PHP

php調用c語言編寫的so動態庫

PHP內核介紹及擴展開發指南


推薦閱讀:

TAG:PHP | PHP擴展 |