Table of Contents
为什么要用C扩展
源码下载
From PHP官网
From Git
From git.php.net
From Github
生成扩展
第一步
第二步
第三步
第四步
第五步
第六步
第七步
参考
Home Backend Development PHP Tutorial PHP的C扩展开发入门指南

PHP的C扩展开发入门指南

Jun 23, 2016 pm 01:11 PM

为什么要用C扩展

C是静态编译的,执行效率比PHP代码高很多。同样的运算代码,使用C来开发,性能会比PHP要提升数百倍。IO操作如CURL,因为耗时主要在IOWait上,C扩展没有明显优势。

另外C扩展是在进程启动时加载的,PHP代码只能操作Request生命周期的数据,C扩展可操作的范围更广。

源码下载

From PHP官网

http://php.net/downloads.php
Copy after login

From Git

git clone https://github.com/php/php-src.git
Copy after login

From git.php.net

git clone http://git.php.net/repository/php-src.git
Copy after login

From Github

  1. 打开 php-src project page
  2. 选择感兴趣的分支
  3. 点击 Download ZIP即可

这里以zip为例:

wget http://museum.php.net/php5/php-5.3.16.tar.gztar zxvf php-5.3.16.tar.gzmv php-5.3.16 php-src
Copy after login

进入到PHP源码目录:

cd php-src	
Copy after login

若使用 Git好处是方便切换不同版本

git clone http://git.php.net/repository/php-src.gitPHP 5.4: git checkout PHP-5.4   PHP 5.5: git checkout PHP-5.5   PHP 5.6: git checkout PHP-5.6   PHP 7.0: git checkout PHP-7.0   PHP HEAD: git checkout master
Copy after login

生成扩展

cd ext
Copy after login

第一步

生成PHP扩展骨架:

./ext_skel --extname=myext
Copy after login

ext_skel是PHP官方提供的用于生成php扩展骨架代码的工具

成功创建完基本文件之后会提示如下:

Creating directory myextCreating basic files: config.m4 config.w32 .svnignore myext.c php_myext.h CREDITS EXPERIMENTAL tests/001.phpt myext.php [done].To use your new extension, you will have to execute the following steps:1.  $ cd ..2.  $ vi ext/myext/config.m43.  $ ./buildconf4.  $ ./configure --[with|enable]-myext5.  $ make6.  $ ./php -f ext/myext/myext.php7.  $ vi ext/myext/myext.c8.  $ makeRepeat steps 3-6 until you are satisfied with ext/myext/config.m4 andstep 6 confirms that your module is compiled into PHP. Then, start writingcode and repeat the last two steps as often as necessary.
Copy after login

查看生成的文件:

tree myext|-- CREDITS|-- EXPERIMENTAL|-- config.m4|-- config.w32|-- myext.c|-- myext.php|-- php_myext.h`-- tests    `-- 001.phpt1 directory, 8 files
Copy after login

config.m4是AutoConf工具的配置文件,用来修改各种编译选项。

第二步

修改 config.m4

cd ..vi ext/myext/config.m4
Copy after login

dnl PHP_ARG_WITH(myext, for myext support,dnl Make sure that the comment is aligned:dnl [  --with-myext             Include myext support])
Copy after login

修改为

PHP_ARG_WITH(myext, for myext support,[  --with-myext             Include myext support])
Copy after login

下边还有一个 –-enable-myext,是表示编译到php内核中。with是作为动态链接库载入的。

第三步

修改 php_myext.h,在45行找到 PHP_FUNCTION(confirm_myext_compiled), 这里就是扩展函数声明部分;

可以增加一行 PHP_FUNCTION(myext_helloworld);, 表示声明了一个myext_helloworld的扩展函数。

第四步

修改 myext.c, 这个是扩展函数的实现部分 在42行之后, 加入 PHP_FE(myext_helloworld, NULL)

const zend_function_entry myext_functions[] = {    PHP_FE(confirm_myext_compiled,  NULL)       /* For testing, remove later. */    PHP_FE(myext_helloworld,  NULL)    PHP_FE_END  /* Must be the last line in myext_functions[] */};
Copy after login

这的代码是将函数指针注册到Zend引擎,增加一行PHP_FE(myext_helloworld, NULL)(后面不要带分号)。

第五步

在 myext.c末尾加myext_helloworld的执行代码。

PHP_FUNCTION(myext_helloworld){    char *arg = NULL;	int arg_len, len;	char *strg;	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {		return;	}	php_printf("Hello World!\n");	RETURN_TRUE;}
Copy after login

zend_parse_parameters是用来接受PHP传入的参数,RETURN_XXX宏是用来返回给PHP数据。

第六步

在myext目录下依次执行:

phpize./configuremakemake install
Copy after login

如果执行 ./configure时出现此错误: configure: error: Cannot find php-config. Please use Cwith-php-config=PATH 说明php-config配置文件不在缺省目录里, 重新执行: ./configure --with-php-config=/usr/local/php/bin/php-config节课 这个文件通常是在PHP的安装目录的bi目录下的一个叫做 php-config或者 php-config5的文件

然后修改php.ini加入 extension = "myext.so"

第七步

通过执行 php -r "myext_helloworld('test');"验证扩展是否成功加载,如果成功则输出 hello world!

参考

  • http://php.net/git.php
  • http://rango.swoole.com/archives/152
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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles