Using C ++ with PHP

xiaoxiao2021-03-06  40

Before we begin

Before we begin, I should note that the focus of this article will be on the UNIX side of the PHP world. I'll mention a few pointers for Windows development, but since I do most of my coding on UNIX systems, I'll Be sticking to what i know for the most morture.

I Should Also Ment That Sse The constructions Should Work with PHP 4.2.x and 4.3.x.

Now, Here's A Few Conventions I'll Use Throughout this Article ...

$ PHP_HOME will refer to the path to your PHP source code, ie where you unpacked your PHP source. On my system, it's / home / jay / setup / php / php-xxx The example module we'll be creating will be called cppext .

The setup

Before you get to coding your extension for PHP in C , you'll need to get yourself a basic extension skeleton. In the UNIX world, you'll want to run a shell script found in $ PHP_HOME / ext called ext_skel. Switch over to The $ PHP_HOME / EXT DIRECTORY AND Fire Up The shell script. Use the --extname argument to give your extension a name.

Jay @ monty ~ $ cd setup / php / pHP-4.3.1 / ext

Jay @ Month Ext $ ./ext_skel --extName CPPEXT

On Windows systems, there's PHP script in $ PHP_HOME / ext called ext_skel_win32.php in the current PHP CVS HEAD. It'll probably become a part of PHP 5 and may be included in future versions of the PHP 4.x branch. I have No IDea if it works, but the daring allowment ...

You Should Now Have A Basic PHP Extension Ready To Go In $ PHP_HOME / EXT / CPPEXT. The Only Problem IS, IT'S All Done In C and NOT IN C .

Setting up the config.m4 file

NOW WOULD BE A Good Time To Open Up Your Extension's Config.m4 File and Get It Ready for Some C Action. This section section geared Towards PHP 4.2.X, But it Should Still Work In PHP 4.3.X.There Isn't Much you have to change here Basically, you want to tell PHP's build system that it should be prepared to use C and link with the standard C library Here's a sample file for our little cppext extension, minus all of the auto-generated comments..:

PHP_ARG_ENABLE (CPPEXT, For CPPEXT Support,

[--Nable-cppext enable cppext support]

)

If Test "$ PHP_CPPPEXT"! = "no"; then

PHP_ADD_LIBRARY (STDC , 1, CPPEXT_SHARED_LIBADD)

PHP_EXTENSION (CPPEXT, $ ext_shared)

PHP_REQUIRE_CXX ()

Fi

In PHP 4.3.x, The Config.m4 File Can Be Set Up A Little Differently, But The Above Should Still Work Fine.

Setting up the makefile.in file

Now you'll.in file. In PHP 4.3.X, this file Won't exist, so you'll Have to create it. The build system in php 4.3.0 Got Rid of this file, But it will stop.

In this file, you want to tell the build system which files it Should Compile Using your C Compiler. There's Not much Difference As Compared to the stock makefile.in That ext_skel creates in php 4.2.x ...

LTLIBRARY_NAME = libcppext.la

LTLIBRARY_SOURCES_CPP = CPPEXT.CPP

LTLIBRARY_SHARED_NAME = CPPEXT.LA

LTLIBRARY_OBJECTS_X = CPPEXT.LO

INCLUDE $ (TOP_SRCDIR) /BUILD/Dynlib.mk

Setting up the source

With config.m4 and makefile.in in place, you can start set setting up your code. Rename cppext.c to a more cish name. FOLLOWING Our Example makefile.in, rename it to cppext.cpp.

Now you can start editing the file. If you were to try and build the extension in it's current state, odds are it would compile without any errors as a shared object, but it probably would not work with PHP. If you compiled it statically into PHP Itself, You'D Probably Get Some Linker Errors. This is Due To Various Difference In C (Which Is What Your Extension Will Be Written in). Think Name MANGLING AND THAT OF Thing.to Remedy this, You'll Need to Tell Your Extension to Treat A Few PHP API Functions As I WERE WRITTEN IN C (Which the aire ".

You'll Need to Wrap A Few Lines with Begin / End_Extern_c (). Specifically You'll Want Your Cppext.cpp To Look Like this:

Extern "C" {

#include "php.h"

#include "php_ini.h"

#include "ext / standard / info.h"

}

.

.

.

#ifdef compile_dl_cppext

Begin_extern_c ()

Zend_Get_Module (CPPext)

END_EXTERN_C ()

#ENDIF

Normally, we'd want to wrap the header files above in BEGIN / END_EXTERN_C () as we did for ZEND_GET_MODULE (cppext), but since BEGIN / END_EXTERN_C () are defined in zend.h, extern "C" will have to do.

In Windows, You May Find That Visual C Complains About Linking Your Extension. You May NEED TO PUT SOMETHING LIKE THIS NEAR THE TOP OF Your Extension:

#ifdef php_win32

#include

#include

#ENDIF

................ ..

Compiableing the extension

Now you're ready to compile your extension. If you want to compile the extension statically (compile into PHP as a part of PHP itself), go down to the PHP root directory at $ PHP_HOME, move the configure file out of the way and Run Buildconf.next, Run Configure With Your Normal Set of Configuration Options and add --enable-cppext. Run Make Clean, Make, Make Install And All That Other Jazz, Like Recompiling Apache and All That.

If you want to compile the extension as a loadable object, head to your extension's directory and run the phpize command. (This assumes that you have PEAR installed on your system.) Phpize will create a configure script just for your little extension. Run configure Make and make install. If you want the extension to load automatic or you'll how to shape your php.ini file to load the proper file. adding a line like extension = cppext.so kind do the trick.

YOUR EXTENSION SHOULD NOW BE Compiled and Ready To Use by PHP. Try Running The Auto-generated cppext.php file found in your extension's source directory to see know.

Mapping C Classes to PHP

There Are A Ton of Ways You Can About Doing This, But Here's A Few Tips To Get You Started.

Start of by making a global zend_class_entry for each class. You also need to have a list entry to handle the destructors for your actual C objects, which we'll actually be treating as PHP resources. (See Note 1 in the exmaple code.) Put all of your methods into your function_entry array. for each class, make another function_entry for the methods you want to map. (See Note 2 in example code.) your MINIT function should initialize the class entries, list entries, etc. (See Note 3.) in your PHP class constructor, you need to register a resource within the PHP class. This resource (handle in the example code) is used to reference the actual C object in method calls. (See Note 4.) Map your PHP methods onto the C class methods. (See Note 5.) That's pretty much it. of course, there are a ton of ways to get the same effect, but this one's pretty simple and should be a decent guide to get you going.

Example Code

Here's some example code to get you going This is pretty simple stuff -. We have a single C class that we map to PHP The C class is simple and does not do much, but you should be able to figure out the harder. Stuff if you can understand THIS ...

CONFIG.M4

DNL Config.m4 for Extension CPPEXT

PHP_ARG_ENABLE (CPPEXT, WHETER TO ENABLE CPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPEXT Support,

[--enable-cppext enable cppext support])

If Test "$ PHP_CPPPEXT"! = "no"; then

PHP_ADD_LIBRARY (STDC , 1, CPPEXT_SHARED_LIBADD)

PHP_NEW_EXTENSION (CPPEXT, CPPEXT.CPP Class.cpp, $ ext_shared)

PHP_REQUIRE_CXX ()

Fi

Makefile.in

LTLIBRARY_NAME = libcppext.la

LTLIBRARY_SOURCES_CPP = CPPEXT.CPP

LTLIBRARY_SHARED_NAME = CPPEXT.LA

LTLIBRARY_SHARED_LIBADD = $ (cppext_shared_libadd) LTLIBRARY_OBJECTS_X = CPPEXT.LO CLASS.LO

INCLUDE $ (TOP_SRCDIR) /BUILD/Dynlib.mk

Class.h - this is for ou Actual C Class ...

#ifndef __class_h__

#define __class_h__

#include

Using namespace std;

Class myphpclass

{

Private:

String itsstring;

PUBLIC:

MyphpClass (String S = "default");

Void setString (const string s);

String getstring () const;

}

#ENDIF

Class.cpp - The MyphPClass IMPLEMENTATION ...

#include "class.h"

Myphpclass :: MyphPClass (String S)

{

ITSString = S;

}

Void myphpclass :: setstring (const string s)

{

ITSString = S;

}

String myphpclass :: getString () const

{

Return itString;

}

PHP_CPPEXT.H - OUR PHP WRAPPER HEADER. Be Careful with Putting Actual C Code In here, as the c compiler used to build php may choke on it during static builds.

#ifndef php_cppext_h

#define php_cppext_h

EXTERN ZEND_MODULE_ENTRY CPPEXT_MODULE_ENTRY

#define phpext_cppext_ptr & CPPEXT_MODULE_ENTRY

#ifdef php_win32

#define php_cppext_api __declspec (dllexport)

#ELSE

#define php_cppext_api

#ENDIF

#ifdef zts

#include "tsrm.h"

#ENDIF

PHP_MINIT_FUNCTION (CPPEXT);

PHP_Function (MyphPClass);

PHP_Function (myphpclass_getstring);

PHP_Function (myphpclass_setstring);

Static void destroy_myphpclass (zend_rsrc_list_entry * rsrc tsrmls_dc);

#ifdef zts

#define cppext_g (v) TSRMG (cppext_globals_id, zend_cppext_globals *, v)

#ELSE

#define cppext_g (v) (CPPEXT_GLOBALS.V)

#ENDIF

#ENDIF / * PHP_CPPPPPPEXT_H * /

CPPEXT.CPP

#ifdef Have_config_h

#include "config.h"

#ENDIF

#ifdef php_win32

#include

#include

#ENDIF

Extern "C" {

#include "php.h" #include "php_ini.h"

#include "ext / standard / info.h"

}

#include "php_cppext.h"

#include "class.h"

/ * Note 1 - here's the zend_class_entry. You'll Also

Need a list entry for the resources used to store the

Actual C Objects ... * /

Static Zend_Class_ENTRY MyphpClass_ENTRY;

Static Int le_myphpclass;

/ * Note 2 - All of the methods Go Into this

Function_ENTRY. BELOW Are The Actual Methods That

Map ONTO MyphPClass. * /

Function_entry cppext_functions [] = {

PHP_fe (MyphPClass, NULL)

PHP_FE (MyphPClass_getstring, null)

PHP_FE (MyphPClass_setString, Null)

{Null, null, null}

}

Static function_entry myphpclass_methods [] = {

{"getString", php_fn (myphpclass_getstring), null},

{"setstring", php_fn (myphpclass_setstring), null},

{Null, null, null}

}

/ * {{CPPEXT_MODULE_ENTRY

* /

ZEND_MODULE_ENTRY CPPEXT_MODULE_ENTRY = {

#if zend_module_api_no> = 20010901

Standard_Module_Header,

#ENDIF

"cppext",

CPPEXT_FUNCTIONS,

PHP_MINIT (CPPEXT),

NULL,

NULL,

NULL,

NULL,

#if zend_module_api_no> = 20010901

"0.1",

#ENDIF

Standard_Module_Properties

}

/ *}}} * /

#ifdef compile_dl_cppext

Begin_extern_c ()

Zend_Get_Module (CPPext)

END_EXTERN_C ()

#ENDIF

/ * {{PHP_MINIT_FUNCTION

* /

PHP_MINIT_FUNCTION (CPPEXT)

{

/ * Note 3 - Here We Register The Destructor for the myphpclass php Objects,

Which deletes the Actual C Objects. Below That, We Initialize The

Class entry for myphpclass. * /

Le_MYPHPCLASS = Zend_register_list_destructors_ex (Destroy_MyphpClass, Null, "MyphPClass-Obj", Module_Number);

INIT_CLASS_ENTRY (MyphPClass_ENTRY, "MyphPClass", MyphPClass_Methods; Zend_Register_internal_class (& myphpclass_entry tsrmls_cc);

RETURN SUCCESS;

}

/ *}}} * /

/ * {{{proProto myphpclass object myphpclass ()

Returns a new myphpclass object. This is basically the constructor. * /

PHP_Function (MyphPClass)

{

/ * Note 4 - here's the constructor. First, initalize return_value as an

Object, Then Make a Handle to the C Object. Register the Handle Asia Resource

And Store The Resource Within The PHP Object So We Can Get To It in The Method

Calls. * /

Myphpclass * obj;

ZVAL * HANDLE;

IF (zend_num_args ()! = 0) {

WRONG_PARAM_COUNT;

}

Obj = new myphpclass;

Object_init_ex (Return_Value, & myphPClass_ENTRY);

Make_std_zval (handle);

Zend_register_resource (Handle, Obj, Le_MYPCLASS);

ZEND_HASH_UPDATE (Z_ObjProp_p (Return_Value), "Handle", SizeOf ("Handle"), & Handle, SizeOf (ZVAL *), NULL);

}

/ *}}} * /

/ * Note 5 - this Macro Gets The Resource Handle for the C Object So We can

Use the c Object in Our Methods mappings best. * /

#define CPP_GET_THIS () /

ID = getTHIS (); /

IF (! id) {/

PHP_ERROR (E_ERROR, "this isn't An Object ?!% s ()", get_active_function_name (TSRMLS_C)); /

} /

IF (Z_OBJPROP_P (ID), "Handle", SIZEOF ("Handle"), (void **) & handle) == Failure) {/

PHP_ERROR (E_ERROR, "underlying Object missing, can't find 'this' IN% s ()", get_active_function_name (TSRMLS_C)); /

} /

Obj = (myphpclass *) zend_list_find (z_lval_pp (handle), & type); /

IF (! Obj || Type! = Le_MYPHPCLASS) {/

PHP_ERROR (E_ERROR, "underlying object is of wrong type in% s ()", get_active_function_name (tsrmls_c)); /}

/ * {{{proProto string myphpclass-> getString ()

Passthru to myphpclass :: getString (). * /

PHP_Function (myphpclass_getstring)

{

Myphpclass * obj;

ZVAL * ID, ** HANDLE;

INT TYPE;

CPP_GET_THIS ();

Return_stringl ((char *) Obj-> getString (). C_str (), obj-> getString (). Length (), 1);

}

/ *}}} * /

/ * {{{Proto Bool MyphPClass-> setstring (string)

Passthru to myphpclass :: setstring (string). * /

PHP_Function (myphpclass_setstring)

{

Myphpclass * obj;

ZVAL * ID, ** HANDLE;

INT TYPE, LEN;

Char * STR;

IF (Zend_Parse_Parameters (Zend_Num_args () TsRMLS_CC, "S", & STR, & LEN) == Failure) {

Return_false;

}

Else {

CPP_GET_THIS ();

Obj-> setString (STR);

Return_True;

}

}

/ *}}} * /

/ * {{{DESTRUCTOR for myphpclass objects * /

Static void destroy_myphpclass (Zend_RSRC_LIST_ENTRY * RSRC TSRMLS_DC)

{

Delete (myphpclass *) RSRC-> PTR;

}

/ *}}} * /

WHERE to Go from here

Now that you have a working PHP extension written in C , you can start using all of C 's features with PHP. Start making some classes, or wrapping PHP extensions around C libraries. The possibilities are finite!

For a more advanced example and various C tricks like classes, pure abstract virtual stuff and all of that nonsense, you can review the source for a PHP extension I wrote in C called cryptopp-php, which can be found at http: // www .TutorBuddy.com / Software /. There's Plenty in There To See and Perhaps Get Some Ideas from.

Have Fun with your c and php, you OOP NUT.

转载请注明原文地址:https://www.9cbs.com/read-58510.html

New Post(0)