Reputation: 1805
I have come across a C library from which I want to use functions inside PHP. This question has put me on track of php-cpp. But it is not very clear to me anywhere if I can use php-cpp for pure C.
Most sources on the internet say it's trivial to mix C with C++, so I want to know if it's worth investing my time learning what I need to learn to achieve the goal.
Upvotes: 3
Views: 474
Reputation: 1835
Yes, you can mix C into C++ within PHP-CPP, however it is not a good approach for beginners because you have to understand the related API's for both.
For those up to the task, you will need to include the appropriate header files from PHP as if you were writing a standard C extension, such as
#include <php.h>
#include <php_globals.h>
#include <php_main.h>
#include <php_network.h>
// etc
You will also need to modify the Makefile for your PHP-CPP project and add the accurate include dirs for your PHP source location, for me its
COMPILER_FLAGS = -I/usr/local/include/php -I/usr/local/include/php/main ... etc ... -Wall -c -O2 -std=c++11 -fpic -o
Add standard PHP/ZEND API C code into your PHP-CPP functions/classes
Php::Value example(Php::Parameters ¶ms)
{
zval myval;
zend_string *hello, *world;
hello = zend_string_init("hello", strlen("hello"), 0);
/* Stores the string into the zval */
ZVAL_STR(&myval, hello);
/* Reads the C string, from the zend_string from the zval */
php_printf("The string is %s", Z_STRVAL(myval));
world = zend_string_init("world", strlen("world"), 0);
/* Changes the zend_string into myval : replaces it by another one */
Z_STR(myval) = world;
zend_string_release(hello);
zend_string_release(world);
return Php::Value(Z_STRVAL(myval));
}
Upvotes: 1
Reputation:
PHP-CPP is a C++ library that can be used to develop PHP extensions. It is not required to develop PHP extensions, although it may make your life a little easier. If you don't know C++, or if you don't want to use it, you can safely ignore PHP-CPP. Refer to "Getting Started with PHP Extension Development" for some resources on developing PHP extensions (in C).
It is perfectly possible to call C libraries from C++. In most cases, the exact same syntax can be used; at most, you may need to wrap C header files with extern "C" { ... }
.
Upvotes: 1
Reputation: 447
But it is not very clear to me anywhere if I can use php-cpp for pure C.
If you try to include any C++ code that actually has C++ features that C does not support in a C program. It simply won't compile.
Most sources on the internet say it's trivial to mix C with C++
That is only the case when you including C code to a C++ program. Even then, there are a few exceptions.
If you are doing this because you do not know C++, you can write a C++ program as if it were C (with a few exceptions, like void pointers) if you are careful enough.
Upvotes: 2