Table of Contents
C/C++ to develop PHP extensions
Prelude to the php extension function
First generate the "skeleton":
In the header file Declare the name of the PHP extension function to be written in php_mttest.h
Add the declaration of the get_log_title function to the zend_function_entry declaration in mytest.c
Compile and test
Home Backend Development PHP Tutorial The first useful PHP extension

The first useful PHP extension

Aug 08, 2016 am 09:24 AM
function php return zend

C/C++ to develop PHP extensions

I feel that for PHP developers, there are very complex and many things to learn. Of course, developing PHP extensions is also a skill that must be mastered. Here I pay homage to the great bird brother ( Laruence)~
The first functional extension to be developed today. Its main function is to generate the date part in front of the log when recording the log

<code>#即使当前的时间,年-月-日 时:分:秒 时间戳.微妙数 
[2015-05-19 20:39:32 1432039172.968199]</code>
Copy after login

Prelude to the php extension function

First generate the "skeleton":
<code>1. 进入php源码src/ext目录下面
2. 运行./ext_skel --extname=mytest
3. 进入src/ext/mytest/目录
4. 在编写扩展的时候要先修改下config.me文件的10-12行,去掉前面的dnl注释,这个网上一搜一大把。</code>
Copy after login
In the header file Declare the name of the PHP extension function to be written in php_mttest.h
<code>PHP_FUNCTION(get_log_title);
#PHP_FUNCTION是PHP内核中声明的一个宏
#define PHP_FUNCTION 		ZEND_FUNCTION    //在文件src/main/php.h : 347行
#define ZEND_FUNCTION(name) ZEND_NAMED_FUNCTION(ZEND_FN(name))		//文件src/Zend/zend_API.h : 68行
#define ZEND_FN(name) 		zif_##name		//文件src/Zend/zend_API.h : 65行
#define ZEND_NAMED_FUNCTION(name) void name(INTERNAL_FUNCTION_PARAMETERS)	//文件src/Zend/zend_API.h : 67行
#define INTERNAL_FUNCTION_PARAMETERS int ht, zval *return_value, zval **return_value_ptr, zval *this_ptr, int return_value_used TSRMLS_DC	//src/Zend/zend.h : 290行</code>
Copy after login

The above declaration function macro is expanded to:

<code>void zif_get_log_title( int ht, zval *return_value, zval **return_value_ptr, zval *this_ptr, int return_value_used TSRMLS_DC)</code>
Copy after login
Add the declaration of the get_log_title function to the zend_function_entry declaration in mytest.c
<code>const zend_function_entry logs_functions[] = {
        PHP_FE(confirm_logs_compiled,   NULL)           /* For testing, remove later. */
		PHP_FE(get_log_title, NULL)
        PHP_FE_END      /* Must be the last line in logs_functions[] */
};
#编写函数
PHP_FUNCTION(get_log_title)
{
    struct timeval tv;
    time_t rawtime;
    struct tm *timeinfo;
    char *formatinfo;
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    gettimeofday(&tv, NULL);
    spprintf(&formatinfo, 0, "[%4d-%02d-%02d %d:%d:%d %d.%d]", 1900 + timeinfo->tm_year, 1 + timeinfo->tm_mon, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, tv.tv_sec, tv.tv_usec);
    RETURN_STRING(formatinfo, 1);
}</code>
Copy after login

There is also a macro to look at here RETURN_STRING

<code>#define RETURN_STRING(s, duplicate) 	{ RETVAL_STRING(s, duplicate); return; }		//文件src/Zend/zend_API.h : 635行
#define RETVAL_STRING(s, duplicate) 	ZVAL_STRING(return_value, s, duplicate)			//文件src/Zend/zend_API.h : 623行
#define ZVAL_STRING(z, s, duplicate) do {	\	//文件src/Zend/zend_API.h : 577-583行,这个的作用其实是给一个string类型zval变量赋值
	const char *__s=(s);				\		
	zval *__z = (z);					\
	Z_STRLEN_P(__z) = strlen(__s);		\		//设置zval字符串长度
	Z_STRVAL_P(__z) = (duplicate?estrndup(__s, Z_STRLEN_P(__z)):(char*)__s);\	//设置zval字符串的值
	Z_TYPE_P(__z) = IS_STRING;			\		//设置zval字符串的类型为字符串
} while (0)</code>
Copy after login

Therefore, RETURN_STRING(formatinfo, 1) is expanded to:

<code>do {
	const char *__s=(formatinfo);
	zval *__z = (return_value);			//这里面的return_value估计是内核定义的,类似 zval *return_value;
	(*__z).value.str.len = strlrn(__s);		//等价于__z->value.str.len
	(*__z).value.str.val = (1?estrndup(__s, (*__z).value.str.len):(char*)__s);
	(*__z).type = 6;	
}</code>
Copy after login
Compile and test
<code>编译的时候需要安装好的php,比如我的php安装在/usr/local/php/目录下面

cd mytest;		//今日刚才编写的函数扩展目录
/usr/local/php/bin/phpize 	//运行phpize,生成configure文件
./configure --with-php-config=/usr/local/php/bin/php-config 	//configure,后面的--with-php-config会生成so文件到安装好的扩展目录,当然也可以不用加,声称之后手动copy过去
make	//有错误的话修正
make install 	//运行之后会提示类似下面的内容
#Installing shared extensions:     /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/
#修改配置文件php.ini添加extension = mytest.so
#测试
php -r 'var_dump(log_get_title());'</code>
Copy after login

If you output the following content, congratulations on your success

<code>[root@iforever logs]# php -r 'var_dump(get_log_title());' && date
string(39) "[2015-05-19 22:52:29 1432047149.755613]"
2015年 05月 19日 星期二 22:52:29 CST</code>
Copy after login

5/19/2015 10:54:38 PM

The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the consent of the author. After reprinting the article, the author and the original text link must be provided in an obvious position on the article page, otherwise the right to pursue legal liability is reserved.

The above introduces the first useful PHP extension, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

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

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.

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

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.

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.

See all articles