search
HomeBackend DevelopmentPHP Tutorial用C编写你自己的php扩展

本文参考:http://blog.csdn.net/taft/article/details/596291

如果你没写过php扩展,又是追求性能的极客,那么这篇文章肯定适合你:

假如你有这样一个php程序

function self_concat($string, $n){    $result = "";    for($i = 0; $i   <br> 如果传入的第二个参数N很大,程序的性能如何?我在自己的机器上测试下如果 n=10000000的时候耗时0.6s左右 如果用C写这个php function然后php直接调用,会快么?那就开始写这样一个简单的扩展吧,采用静态编译成.so的方式来加载,我用最快最简明的方式说明。  <p></p>  <p>1.首先你需要有php的源码目录 cd到其ext目录下执行:</p>  <p></p>  <pre name="code" class="sycode">./ext_skel --extname=luckyext --proto=luckyext.def

这条命令会自动生成一个名叫luckyext的目录 里面有基本的扩展骨架文件,核心的文件只有三个 congif.m4用来做编译配置,luckyext.h定义都文件包括声明你的自定义函数,还有luckyext.c用来写C的函数源码,其他都是附加的骨架文件,暂时可以不用管。

2.在luckyext.c内编写你要的函数,记得在头文件内声明,不然编译的时候会报错

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

3.编译扩展 关于php的环境配置就不说了

phpize./configuremake&&make install

成功编译的话会在你的php指定的扩展目录中生成一个luckyext.so的文件

4.引入扩展重新加载php

vi /etc/php.iniextension=luckyext.so
我是mac机,修改的时候请看自己机器的配置,修改完后保存重启fpm
killall php-fpmphp-fpm

5.测试

终端输入

php -m
出来的扩展中应该有luckyext了,至于它支持什么函数 可以用ext/luckyext目录内的luckyext.php脚本去运行看看 正常情况会输出它支持的函数self_concat_c()

6.性能对比 直接运行C写的php

<?phpself_concat_c ('fire',10000000);

出来的结果耗时是惊人的,0.06秒,相差10倍!为什么呢,因为如果用php那套代码,每次往字符串塞字符的时候,php都需要做一个内存的动态分配,循环越多次,性能开销就越大,而C写的function直接就计算出最终需要分配多少内存了,所以快就快在这里,是不是很有趣~哈哈,至少我觉得很刺激!

本文的C例子属参考前辈翻译的文件,以后要多修修C的功底才行了,后面我会研究更多C的知识,加油!

Statement
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
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function