Search code examples
phpc++php-extension

How to call function from .so file using php script?


I have created .so file for following function:

main.cpp:

#include<stdio.h>
#include "test.h"
int main()
{
int a=hello();
printf("%d",a);
return 0;
}

test.h

int test()
{
 int a=5,b=10,c;
 printf("Hi");
 c=a+b;
 return c;
}

Now I create shared library file main.so for above program and want to call hell() function from php script.

p1.php

<?php
// Call to test function in main.cpp
>

I saw various tutorials on web but no clear explaination. Can someone give link to some tutorial or help me for this prob?


Solution

  • Sara Goleman's book is an excellent, thorough coverage of how to develop php extensions (including your topic).

    Here is an introductory article.

    http://devzone.zend.com/303/extension-writing-part-i-introduction-to-php-and-zend/

    I've read her book and it covers this question entirely.

    http://www.amazon.com/dp/067232704X

    I'm sorry if this isn't a quick and easy answer. However, the PHP API isn't exactly straight forward. It didn't quite make sense without further background information on each of the components. Once I had that, I was able to see PHP API development clearly.

    Alternatively, if you're looking for a different approach, using RabbitMQ or some other message queue service may be desirable to invoke a c++ application and send messages back and forth from (optionally) a persistent c++ process.

    Here are some further links that I've found to be useful:

    http://devzone.zend.com/1435/wrapping-c-classes-in-a-php-extension/

    http://talks.somabo.de/200903_montreal_php_extension_writing.pdf

    http://simonholywell.com/post/2010/09/15-excellent-resources-for-php-extension-development.html

    http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html

    http://www.php.net/manual/en/internals2.php