在php程序中需要用到C 代码,应该是下面两种情况:
1 已有C代码,在php程序中想直接用
2 由于php的性能问题,需要用C来实现部分功能
针对第一种情况,最合适的方法是用system调用,把现有C代码写成一个独立的程序。参 数通过命令行或者标准输入传入,结果从标准输出读出。其次,稍麻烦一点的方法是C代码写成一个daemon,php程序用socket来和它进行通讯。
重 点讲讲第二种情况,虽然沿用system调用的方法也可以,但是想想你的目的是优化性能,那么频繁的起这么多进程,当然会让性能下降。而写daemon的 方法固然可行,可是繁琐了很多。
我的简单测 试,同样一个算法,用C来写比用php效率能提高500倍。而用php扩展的方式,也能提高90多倍(其中的性能损失在了参数传递上了吧, 我猜)。
所以有些时候php扩展就是我们的最佳选择了。
这里我着重介绍一下用C写php扩展的方法,而且不需要重新编译 php。
首先,找到一个php的源码,php4或者php5版本的都可以,与你目标平台的php版本没有关系。
在源码的 ext目录下可以找到名为ext_skel的脚本(windows平台使用ext_skel_win32.php)
在这个目录下执 行./ext_skel --extname=hello(我用hello作为例子)
这时生成了一个目录 hello,目录下有几个文件,你只需要关心这三个:config.m4 hello.c php_hello.h
把这个目录拷备到任何 你希望的地方,cd进去,依次执行
phpize
./configure
make
什么也没发生,对吧?
这是因为漏 了一步,打开config.m4,找到下面
dnl If your extension references something external, use with:
...
dnl Otherwise use enable:
...
这 是让你选择你的扩展使用with还是enable,我们用with吧。把with那一部分取消注释。
如果你和我一样使用vim编辑器,你就会很容 易发现dnl三个字母原来是表示注释的呀(这是因为vim默认带了各种文件格式的语法着色包)
我们修改了config.m4后,继续
phpize
./configure
make
这 时,modules下面会生成hello.so和hello.la文件。一个是动态库,一个是静态库。
你的php扩展已经做好了,尽管它 还没有实现你要的功能,我先说说怎么使用这个扩展吧!ext_skel为你生成了一个hello.php里面有调用示例,但是那个例子需要你把 hello.so拷贝到php的扩展目录中去,我们只想实现自己的功能,不想打造山寨版php,改用我下面的方法来加载吧: if(!extension_loaded("hello")) {
dl_local("hello.so");
}
function dl_local( $extensionFile ) {
//make sure that we are ABLE to load libraries
if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
die( "dh_local(): Loading extensions is not permitted.\n" );
}
//check to make sure the file exists
if( !file_exists(dirname(__FILE__) . "/". $extensionFile ) ) {
die( "dl_local(): File '$extensionFile' does not exist.\n" );
}
//check the file permissions
if( !is_executable(dirname(__FILE__) . "/". $extensionFile ) ) {
die( "dl_local(): File '$extensionFile' is not executable.\n" );
}
//we figure out the path
$currentDir = dirname(__FILE__) . "/";
$currentExtPath = ini_get( "extension_dir" );
$subDirs = preg_match_all( "/\//" , $currentExtPath , $matches );
unset( $matches );
//lets make sure we extracted a valid extension path
if( !(bool)$subDirs ) {
die( "dl_local(): Could not determine a valid extension path [extension_dir].\n" );
}
$extPathLastChar = strlen( $currentExtPath ) - 1;
if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
$subDirs--;
}
$backDirStr = "";
for( $i = 1; $i <= $subDirs; $i++ ) {
$backDirStr .= "..";
if( $i != $subDirs ) {
$backDirStr .= "/";
}
}
//construct the final path to load
$finalExtPath = $backDirStr . $currentDir . $extensionFile;
//now we execute dl() to actually load the module
if( !dl( $finalExtPath ) ) {
die();
}
//if the module was loaded correctly, we must bow grab the module name
$loadedExtensions = get_loaded_extensions();
$thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];
//lastly, we return the extension name
return $thisExtName;
}//end dl_local()
- 登录 发表评论
评论