Wrapping C++ Classes in a PHP Extension

I have a tutorial at the Zend Developer Zone called Wrapping C++ Classes in a PHP Extension. It walks you through writing a simple PHP extension that wraps a class written in C++. This is a useful thing to be able to do, especially when exposing an already existing library’s API to PHP userland scripts, which seems like a fairly common task.

6 Comments

  1. mark
    Posted May 1, 2009 at 6:01 pm | Permalink

    Thanks!…..can you write an article about how to load an *.lib or *.dll on windows…..

  2. Posted May 1, 2009 at 6:15 pm | Permalink

    Hi Mark, thanks for the feedback. I may have a reason to port an existing C++ extension to Windows so I’ll likely be researching the Windows build process quite a bit. I’ll make sure to write something up on that topic if I do end up doing it.

  3. Pedro
    Posted May 16, 2009 at 9:56 pm | Permalink

    Hello, your tutorial is very useful, thanks for it. Do you know some article that explains “wrappping c functions”?. I think that the process will be very similar but I don’t know clearly how to do it, what do you think?. Thanks

  4. Posted June 9, 2009 at 3:24 am | Permalink

    Hi Pedro, wrapping C functions shouldn’t be an issue at all. PHP is written in C (and most of the extensions you write will be in C) so there really isn’t anything to do… if you have a function in C that you would like to make available to userspace scripts, just call it from a PHP_FUNCTION. The only issue you will have to deal with is converting parameters and return values between zend values and the respective C types. Luckily, unless you are dealing with structs, this too should be relatively simple. Hope that helps!

  5. Pedro2
    Posted June 18, 2009 at 9:16 am | Permalink

    Thanks for your help! Unfortunately, I have to use structs in my PHP extension. Some suggestions for it?

  6. toudi
    Posted July 13, 2009 at 2:13 pm | Permalink

    hi paul – i have read Your tutorial and everything went just fine to the moment i needed to chain a method in c++ class. what i mean by this is i would like to call Car->accelerate()->brake() using Your example and it works in c++ (one only needs to change the return type from void into Car*), but i haven’t found anything similar to RETURN_OBJECT in zend engine so that i could expose those methods to php. how one can accomplish this? do i have to define my own function RETURN_OBJECT? if so, how?

    best regards, toudi

Post a Comment

Your email is never shared. Required fields are marked *

*
*