Home Backend Development PHP Tutorial PHP内核的学习-创办PHP扩展

PHP内核的学习-创办PHP扩展

Jun 13, 2016 pm 12:18 PM
ext php str

PHP内核的学习--创建PHP扩展

开始看PHP内核也有一段时间了,现在开始边学边总结,今天就总结一下如何创建自己的PHP扩展。

我的环境如下:

系统:Ubuntu 14.04

php版本:5.5.19

参考摘录:用C/C++扩展你的PHP

PHP取得成功的一个主要原因之一是它拥有大量的可用扩展。web开发者无论有何种需求,这种需求最有可能在PHP发行包里找到。PHP发行包包括支持各种数据库,图形文件格式,压缩,XML技术扩展在内的许多扩展。

扩展API的引入使PHP3取得了巨大的进展,扩展API机制使PHP开发社区很容易的开发出几十种扩展。现在,两个版本过去了,API仍然和PHP3时的非常相似。扩展主要的思想是:尽可能的从扩展编写者那里隐藏PHP的内部机制和脚本引擎本身,仅仅需要开发者熟悉API。

有两个理由需要自己编写PHP扩展。第一个理由是:PHP需要支持一项她还未支持的技术。这通常包括包裹一些现成的C函数库,以便提供PHP接口。例如,如果一个叫FooBase的数据库已推出市场,你需要建立一个PHP扩展帮助你从PHP里调用FooBase的C函数库。这个工作可能仅由一个人完成,然后被整个PHP社区共享(如果你愿意的话)。第二个不是很普遍的理由是:你需要从性能或功能的原因考虑来编写一些商业逻辑。

假设你正在开发一个网站,需要一个把字符串重复n次的函数。下面是用PHP写的例子:

<span style="color: #0000ff;">function</span> <span style="color: #008080;">util_str_repeat</span>(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$n</span><span style="color: #000000;">){    </span><span style="color: #800080;">$result</span> = ""<span style="color: #000000;">;    </span><span style="color: #0000ff;">for</span>(<span style="color: #800080;">$i</span> = 0; <span style="color: #800080;">$i</span> $n; <span style="color: #800080;">$i</span>++<span style="color: #000000;">){        </span><span style="color: #800080;">$result</span> .= <span style="color: #800080;">$string</span><span style="color: #000000;">;    }    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$result</span><span style="color: #000000;">;} </span><span style="color: #008080;">util_str_repeat</span>("One", 3);<span style="color: #008000;">//</span><span style="color: #008000;"> returns "OneOneOne".</span><span style="color: #008080;">util_str_repeat</span>("One", 1);<span style="color: #008000;">//</span><span style="color: #008000;"> returns "One".</span>
Copy after login

假设由于一些奇怪的原因,你需要时常调用这个函数,而且还要传给函数很长的字符串和大值n。这意味着在脚本里有相当巨大的字符串连接量和内存重新分配过程,以至显著地降低脚本执行速度。如果有一个函数能够更快地分配大量且足够的内存来存放结果字符串,然后把$string重复n次,就不需要在每次循环迭代中分配内存。

为扩展建立函数的第一步是写一个函数定义文件,该函数定义文件定义了扩展对外提供的函数原形。该例中,定义函数只有一行函数原形util_str_repeat() :

<span style="color: #0000ff;">string</span> util_str_repeat(<span style="color: #0000ff;">string</span> str, <span style="color: #0000ff;">int</span> n)
Copy after login

函数定义文件的一般格式是一个函数一行。你可以定义可选参数和使用大量的PHP类型,包括: bool, float, int, array等。

保存为util.def文件至PHP原代码目录树下(即与ext_skel文件放在同一目录下,我的目录是/usr/share/php5/)。

然后就是通过扩展骨架(skeleton)构造器运行函数定义文件的时机了。该构造器脚本就是ext_skel。假设你把函数定义保存在一个叫做util.def的文件里,而且你希望把扩展取名为util,运行下面的命令来建立扩展骨架:

sudo ./ext_skel --extname=util --proto=util.def
Copy after login

执行之后,我这里报了如下错误:

./ext_skel: <span style="color: #800080;">1</span>: cd: can<span style="color: #800000;">'</span><span style="color: #800000;">t cd to /usr/lib/php5/skeleton</span><span style="color: #000000;">Creating directory util</span><span style="color: #0000ff;">awk</span>: cannot open /create_stubs (No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> or directory)Creating basic files: config.m4 config.w32 .svnignore util.c.</span>/ext_skel: <span style="color: #800080;">216</span>: ./ext_skel: cannot open /skeleton.c: No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> php_util.h.</span>/ext_skel: <span style="color: #800080;">234</span>: ./ext_skel: cannot open /php_skeleton.h: No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> CREDITS.</span>/ext_skel: <span style="color: #800080;">238</span>: ./ext_skel: cannot open /CREDITS: No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> EXPERIMENTAL.</span>/ext_skel: <span style="color: #800080;">242</span>: ./ext_skel: cannot open /EXPERIMENTAL: No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> tests</span>/<span style="color: #800080;">001</span>.phpt./ext_skel: <span style="color: #800080;">247</span>: ./ext_skel: cannot open /tests/<span style="color: #800080;">001</span>.phpt: No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> util.php.</span>/ext_skel: <span style="color: #800080;">251</span>: ./ext_skel: cannot open /skeleton.php: No such <span style="color: #0000ff;">file</span><span style="color: #0000ff;">rm</span>: cannot remove ‘function_entries’: No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> or directory</span><span style="color: #0000ff;">rm</span>: cannot remove ‘function_declarations’: No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> or directory</span><span style="color: #0000ff;">rm</span>: cannot remove ‘function_stubs’: No such <span style="color: #0000ff;">file</span><span style="color: #000000;"> or directory [</span><span style="color: #0000ff;">done</span><span style="color: #000000;">].To use your new extension, you will have to execute the following steps:</span><span style="color: #800080;">1</span><span style="color: #000000;">.  $ cd ..</span><span style="color: #800080;">2</span>.  $ <span style="color: #0000ff;">vi</span> ext/util/<span style="color: #000000;">config.m4</span><span style="color: #800080;">3</span>.  $ ./<span style="color: #000000;">buildconf</span><span style="color: #800080;">4</span>.  $ ./configure --[with|enable]-<span style="color: #000000;">util</span><span style="color: #800080;">5</span>.  $ <span style="color: #0000ff;">make</span><span style="color: #800080;">6</span>.  $ ./php -f ext/util/<span style="color: #000000;">util.php</span><span style="color: #800080;">7</span>.  $ <span style="color: #0000ff;">vi</span> ext/util/<span style="color: #000000;">util.c</span><span style="color: #800080;">8</span>.  $ <span style="color: #0000ff;">make</span><span style="color: #000000;">Repeat steps </span><span style="color: #800080;">3</span>-<span style="color: #800080;">6</span> <span style="color: #0000ff;">until</span> you are satisfied with ext/util/<span style="color: #000000;">config.m4 andstep </span><span style="color: #800080;">6</span><span style="color: #000000;"> confirms that your module is compiled into PHP. Then, start writingcode and repeat the </span><span style="color: #0000ff;">last</span> two steps as often as necessary.
Copy after login

很明显是/usr/lib/php5/skeleton路径的错误,编辑ext_skel文件,将/usr/lib/php5/skeleton修改为/usr/share/php5/skeleton,然后移除掉生成的util文件夹,再次执行之前的命令,成功后提示如下:

<span style="color: #000000;">Creating directory utilCreating basic files: config.m4 config.w32 .svnignore util.c php_util.h CREDITS EXPERIMENTAL tests</span>/<span style="color: #800080;">001</span>.phpt util.php [<span style="color: #0000ff;">done</span><span style="color: #000000;">].To use your new extension, you will have to execute the following steps:</span><span style="color: #800080;">1</span><span style="color: #000000;">.  $ cd ..</span><span style="color: #800080;">2</span>.  $ <span style="color: #0000ff;">vi</span> ext/util/<span style="color: #000000;">config.m4</span><span style="color: #800080;">3</span>.  $ ./<span style="color: #000000;">buildconf</span><span style="color: #800080;">4</span>.  $ ./configure --[with|enable]-<span style="color: #000000;">util</span><span style="color: #800080;">5</span>.  $ <span style="color: #0000ff;">make</span><span style="color: #800080;">6</span>.  $ ./php -f ext/util/<span style="color: #000000;">util.php</span><span style="color: #800080;">7</span>.  $ <span style="color: #0000ff;">vi</span> ext/util/<span style="color: #000000;">util.c</span><span style="color: #800080;">8</span>.  $ <span style="color: #0000ff;">make</span><span style="color: #000000;">Repeat steps </span><span style="color: #800080;">3</span>-<span style="color: #800080;">6</span> <span style="color: #0000ff;">until</span> you are satisfied with ext/util/<span style="color: #000000;">config.m4 andstep </span><span style="color: #800080;">6</span><span style="color: #000000;"> confirms that your module is compiled into PHP. Then, start writingcode and repeat the </span><span style="color: #0000ff;">last</span> two steps as often as necessary.
Copy after login

然后采用静态编译的方式编译扩展。为了使扩展能够被编译,需要修改扩展目录util/下的config.m4文件。扩展没有包裹任何外部的C库,你需要添加支持–enable-util配置开关到PHP编译系统里(–with-extension 开关用于那些需要用户指定相关C库路径的扩展)。找到如下内容:

<span style="color: #000000;">dnl PHP_ARG_ENABLE(util, whether to enable util support,dnl Make sure that the comment </span><span style="color: #0000ff;">is</span><span style="color: #000000;"> aligned:dnl [  </span>--enable-util           Enable util support])
Copy after login

将前面的dnl 去掉,修改为如下结果:

<span style="color: #000000;">PHP_ARG_ENABLE(util, whether to enable util support,Make sure that the comment </span><span style="color: #0000ff;">is</span><span style="color: #000000;"> aligned:[  </span>--enable-util           Enable util support])
Copy after login

然后修改util.c文件,找到如下代码:

<span style="color: #000000;">PHP_FUNCTION(util_str_repeat){    </span><span style="color: #0000ff;">char</span> *str =<span style="color: #000000;"> NULL;    </span><span style="color: #0000ff;">int</span> argc =<span style="color: #000000;"> ZEND_NUM_ARGS();    </span><span style="color: #0000ff;">int</span><span style="color: #000000;"> str_len;    </span><span style="color: #0000ff;">long</span><span style="color: #000000;"> n;    </span><span style="color: #0000ff;">if</span> (zend_parse_parameters(argc TSRMLS_CC, <span style="color: #800000;">"</span><span style="color: #800000;">sl</span><span style="color: #800000;">"</span>, &str, &str_len, &n) ==<span style="color: #000000;"> FAILURE)         </span><span style="color: #0000ff;">return</span><span style="color: #000000;">;    php_error(E_WARNING, </span><span style="color: #800000;">"</span><span style="color: #800000;">util_str_repeat: not yet implemented</span><span style="color: #800000;">"</span><span style="color: #000000;">);}</span>
Copy after login

将其修改为如下代码:

<span style="color: #000000;">PHP_FUNCTION(util_str_repeat){    </span><span style="color: #0000ff;">char</span> *str =<span style="color: #000000;"> NULL;    </span><span style="color: #0000ff;">int</span> argc =<span style="color: #000000;"> ZEND_NUM_ARGS();    </span><span style="color: #0000ff;">int</span><span style="color: #000000;"> str_len;    </span><span style="color: #0000ff;">long</span><span style="color: #000000;"> n;    </span><span style="color: #0000ff;">char</span> *result; <span style="color: #008000;">/*</span><span style="color: #008000;"> Points to resulting string </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">char</span> *ptr; <span style="color: #008000;">/*</span><span style="color: #008000;"> Points at the next location we want to copy to </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">int</span> result_length; <span style="color: #008000;">/*</span><span style="color: #008000;"> Length of resulting string </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">if</span> (zend_parse_parameters(argc TSRMLS_CC, <span style="color: #800000;">"</span><span style="color: #800000;">sl</span><span style="color: #800000;">"</span>, &str, &str_len, &n) ==<span style="color: #000000;"> FAILURE)        </span><span style="color: #0000ff;">return</span><span style="color: #000000;">;    </span><span style="color: #008000;">/*</span><span style="color: #008000;"> Calculate length of result </span><span style="color: #008000;">*/</span><span style="color: #000000;">    result_length </span>= (str_len *<span style="color: #000000;"> n);    </span><span style="color: #008000;">/*</span><span style="color: #008000;"> Allocate memory for result </span><span style="color: #008000;">*/</span><span style="color: #000000;">    result </span>= (<span style="color: #0000ff;">char</span> *) emalloc(result_length + <span style="color: #800080;">1</span><span style="color: #000000;">);    </span><span style="color: #008000;">/*</span><span style="color: #008000;"> Point at the beginning of the result </span><span style="color: #008000;">*/</span><span style="color: #000000;">    ptr </span>=<span style="color: #000000;"> result;    </span><span style="color: #0000ff;">while</span> (n--<span style="color: #000000;">) {        </span><span style="color: #008000;">/*</span><span style="color: #008000;"> Copy str to the result </span><span style="color: #008000;">*/</span><span style="color: #000000;">        memcpy(ptr, str, str_len);        </span><span style="color: #008000;">/*</span><span style="color: #008000;"> Increment ptr to point at the next position we want to write to </span><span style="color: #008000;">*/</span><span style="color: #000000;">        ptr </span>+=<span style="color: #000000;"> str_len;    }<br>    </span><span style="color: #008000;">/*</span><span style="color: #008000;"> Null terminate the result. Always null-terminate your strings    even if they are binary strings </span><span style="color: #008000;">*/</span>    *ptr = <span style="color: #800000;">'</span><span style="color: #800000;">\0</span><span style="color: #800000;">'</span><span style="color: #000000;">;    </span><span style="color: #008000;">/*</span><span style="color: #008000;"> Return result to the scripting engine without duplicating it</span><span style="color: #008000;">*/</span><span style="color: #000000;">    RETURN_STRINGL(result, result_length, </span><span style="color: #800080;">0</span><span style="color: #000000;">);}</span>
Copy after login

里面的具体内容,就不在这里说了,之后会慢慢写到。

然后就是编译,安装。在util目录下,命令如下(命令可能都需要加sudo):

<span style="color: #000000;">phpize.</span>/<span style="color: #000000;">configure</span><span style="color: #0000ff;">make</span><span style="color: #0000ff;">make</span><span style="color: #000000;"> test</span><span style="color: #0000ff;">make</span> <span style="color: #0000ff;">install</span>
Copy after login

然后配置生成的扩展文件,在php5.5版本中,进入到/etc/php5/mods-available目录下,创建util.ini文件,写入如下内容:

extension=util.so
Copy after login

然后enable util扩展

<span style="color: #0000ff;">sudo</span> php5enmod util
Copy after login

最后,重启php-fpm

<span style="color: #0000ff;">sudo</span> service php5-fpm restart
Copy after login

创建一个php文件,测试一下,测试文件如下:

<span style="color: #000000;">php</span><span style="color: #0000ff;">for</span> (<span style="color: #800080;">$i</span> = 1; <span style="color: #800080;">$i</span> $i++<span style="color: #000000;">) {    </span><span style="color: #0000ff;">print</span> util_str_repeat("CraryPrimitiveMan ", <span style="color: #800080;">$i</span><span style="color: #000000;">);    </span><span style="color: #0000ff;">print</span> "\n"<span style="color: #000000;">;}</span>?>
Copy after login

执行结果如下:

<span style="color: #000000;">CraryPrimitiveMan CraryPrimitiveMan CraryPrimitiveMan CraryPrimitiveMan CraryPrimitiveMan CraryPrimitiveMan</span>
Copy after login

这样我们就成功创建了一个包含简单的PHP函数的扩展。

盗图一张~~

今天就先到这里~~

 

1楼吉编辑
很不错,感谢分享,有兴趣写书出书吗?
Re: 疯狂的原始人
@吉编辑,水平不够啊。。。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles