SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
Usage Note Of
SWIG for PHP
William.L
wiliwe@gmail.com
2015-08-20
Index
What is SWIG? ..................................................................................................................................................... 3
Install SWIG Tool & Library............................................................................................................................... 4
SWIG for PHP....................................................................................................................................................... 6
Generate and Install PHP Extension................................................................................................................... 7
Use PHP Extension.............................................................................................................................................. 18
What is SWIG?
SWIG, Simplified Wrapper and Interface Generator, is a software development tool for building scripting
language interfaces to C and C++ programs. It is a kind of interface definition/description language (IDL).
Originally developed in 1995, SWIG was first used by scientists in the Theoretical Physics Division at Los
Alamos National Laboratory for building user interfaces to simulation codes running on the Connection
Machine 5 supercomputer.
SWIG was originally designed to make it extremely easy for scientists and engineers to build extensible
scientific software without having to get a degree in software engineering. It simplifies the task of interfacing
different languages to C and C++ programs by largely automating the task of language integration--allowing
developers and users to focus on more important problems.
In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates the wrappers needed to access
those declarations from other languages including Perl, PHP, Python, Tcl, Ruby, Guile, and Java. SWIG
normally requires no modifications to existing code and can often be used to build a usable interface in only a
few minutes.
SWIG official site:
* http://swig.org/
SWIG documentation and tutorial:
* http://swig.org/doc.html
* http://swig.org/tutorial.html
Download SWIG source archive for different operating system platforms:
* http://sourceforge.net/projects/swig/files/
Example codes for this documentation could be downloaded from the GitHub:
https://github.com/wiliwe/swig-php-example
Install SWIG Tool & Library
The environment used in this document:
* Linux CentOS 6.5 64-bit (could be updated to 6.6 or 6.7)
* GCC C/C++ compiler v4.9.0 (which support C++11 and C++14 standards)
* SWIG v3.0.7 (released on 2015-08-03)
(Note that in console/terminal, type “swig -version”, it will show v1.3.40)
* PHP v5.3.3
* Qt Creator v3.3.1 IDE tool
Before installing the SWIG v3.0.7, please remove the old built-in SWIG from CentOS 6.5:
$ su (change to root)
# yum erase swig
Build & Install SWIG tool and libraries
The SWIG tool/library installation guide is described in “Installation” section of chapter 1, “Preface.”
1) Donwload the SWIG v3.0.7 source archive for Unix/Linux, swig-3.0.7.tar.gz, from the site:
http://sourceforge.net/projects/swig/files/swig/swig-3.0.7/
2) Unpack swig-3.0.7.tar.gz to generate a folder named “swig-3.0.7”.
3) Enter the folder “swig-3.0.7” and run below commands to build and install SWIG tool and library:
$ ./configure --prefix=/usr --libdir=/usr/lib64
$ make
$ su (change to root)
# make install
By default SWIG installs itself in “/usr/local”. The installation path could be found in the file config.log
which is under the directory “swig-3.0.7”. In config.log , search “prefix=” and “libdir=” variable
assignments and you could see the installation path.
After installing, run “swig -version” to verify the version of the SWIG is what we set.
4) It could use command “swig -swiglib” tool to find out where SWIG thinks its library is located (be sure
SWIG tool and library are installed properly before running this command).
SWIG for PHP
For PHP scripting language, SWIG generates PHP Extensions (or called modules) for gluing C or C++ codes.
PHP extension is as a dynamically loaded library: in MSFT Windows, it is DLL(.dll) ; in Unix/Linux, it is
SO(.so); in Apple Mac OS X, it is DYLIB(.dylib).
The location of PHP built-in modules could be found from the result of execution of PHP phpinfo() function:
In SWIG documentaiton 3.0 (http://swig.org/Doc3.0/index.html), chapter 4 explain the relationship between
scripting language (pythong, PHP, perl, etc) and C/C++ languages.
Generate and Install PHP Extension
Basic steps of using SWIG are as below:
1) Write a SWIG interface file describing the interface name and its parameter. The interface files usually end
with “.i” extension name which stands for “interface.”
Below snapshots are examples for SWIG interface writing. It could declare all interfaces name in the
interface file or use a header to contain it and include this header file into the interface file.
<Non Header Way>
< Header way>
2) Use SWIG tool(swig) with the written interface file as input to generate files for building out
extension/module file of target language.
Below commands are for building out PHP extensions from C and C++, you could put then into a Make file and
make it. Remember that it MUST run “swig” tool to generate C or C++ wrapping source and header files for
the generation of PHP extension file as the FIRST step.
For generating PHP extension, it needs PHP development library header, so run below commands to install it:
$ su (change to root)
# yum install php-devel.x86_64
<For C>
swig -php swigphp.i (replace “swigphp.i” with your SWIG interface file name)
gcc `php-config --includes` -fpic -c swigphp_wrap.c swigphp.c
gcc -shared swigphp_wrap.o helloswig.o -o swigphp.so
Running “swig” tool for C++ will generate three files:
* swigphp_wrap.c
* php_swigphp.h
* swigphp.php
<For C++>
swig -c++ -php swigphp.i (replace “swigphp.i” with your SWIG interface file name)
g++ `php-config --includes` -fpic -c swigphp_wrap.cpp swigphp.cpp
g++ -shared swigphp_wrap.o swigphp.o -o swigphp.so
Running “swig” tool for C++ will generate three files:
* swigphp_wrap.cpp
* php_swigphp.h
* swigphp.php
Below snapshots show an example of generation and compilation of a PHP extension, helloswigc.so.
Besides command line way, it could use Qt Creator IDE and QMake to build out PHP extension. The Qt
Creator project setup steps are show below. The needed C or C++ source files are needed to be generated
through “swig” tool in advance.
1) Create a whole new Qt project by clicking these items:
“Library” -> “C++ Library”
In project window, remove the Qt Creator generated files.
Add C or C++ source files generated by “swig” tool into Qt Creator project.
* php_SWIG-Module-Name.h
* SWIG-Module-Name _wrap.c (for C)
or
SWIG-Module-Name _wrap.cpp (for C++).
5) In Qt PRO file, change the value of TARGET variable for output file name you want.
6) In Qt PRO file, add below line for searching PHP zend.h file when building.
QMAKE_CXXFLAGS += `php-config --includes`
Also, add C++10 standard supporting flag.
QMAKE_CXXFLAGS += -std=c++0x
7) Uncheck “Projects-> Build & Run -> Shadow build“ for “Debug” and “Release”.
8) Start to build by clicking “Build” button (a hammer icon) on IDE’s side panel.
9) After building out SWIG PHP extension SO file successfully, it will generate the file "libhelloswigc.so.1.0.0"
whose version number may not be “1.0.0”, it is up to your setting.
Change extension file name from " libhelloswigc.so.1.0.0" to "helloswigc.so".
Install PHP Extension
Edit /etc/php.ini , in "Dynamic Extensions" section, add this line:
extension = helloswigc.so
Drop down to change to
Debug or Release.
It could add more than one lines of “extension=” for multiple PHP extension loading.
Save /etc/php.ini and use “php -m” command to verify if it could load new assigned PHP extension
successfully.
If a PHP extension file specified in php.ini does not exist under PHP extension folder, it will show below error
message:
Finally, restart Apache through the commands:
$ su (change to root)
# service httpd restart
Note that the PHP configuration file, php.ini, may locate in other folder. You could find it through put a PHP
page(file name ends with ".php") under /var/www/html folder and the page's contents are as below:
In Web browser, to browse this PHP page, if it could be run successfully, it will show information about PHP.
<?php
phpinfo();
?>
Note
When running “php -m” If it could not find one or more needed libraries the PHP extension
depends on, it will show error message that tell you which library could not be found.
Look at the entry having the string "Loaded Configuration File" , it shows the actual path to php.ini file.
Run below commands in root to put "helloswigc.so" file to PHP module folder.
$ su (change to root)
# cp ./helloswigc.so `php-config --extension-dir`
, where `php-config --extension-dir` option will output the path to PHP module folder.
Note
<1> When building C++ file, it MUST use g++ or c++ instead of gcc compiler, or it will happen error when
loading PHP extension/module that it will say it could not find name mangling/decoration symbol as
below snapshot.
<2> For earlier version of SWIG, if the version of PHP library for building PHP extension is not the same as
the one you will run on, it might show this error message when running “php -m” command:
“Unable to initialize module”
, see below sites for more information:
* http://php.net/manual/en/solr.installation.php
* http://stackoverflow.com/questions/2394532/apache-is-unable-to-initialize-module-because-of-modules-and-phps-api-dont
* http://stackoverflow.com/questions/3130910/php-warning-php-startup-unable-to-initialize-module
Use PHP Extension
Write a PHP file including “swig” tool generated PHP file and call the interface specified in SWIG interface file.
Below snapshot shows an example that helloswigc_test.php includes helloswigc.php which was generated by
“swig” tool.
In Web browser, locate to helloswigc_test.php, if anything is okay, it could show the result what you want.
It could use “php” tool to run PHP page. For example:
$ php -c . /var/www/html/ helloswigc_test.php
Note
If one or more PHP extensions contain more than one identical class names or macro without using namespace
to isolate it, it will cause fatal errors and let Apache Web server crash, it will not boot successfully until the class
name confilict issue is remove.

Weitere ähnliche Inhalte

Was ist angesagt?

Robot Framework :: Demo login application
Robot Framework :: Demo login applicationRobot Framework :: Demo login application
Robot Framework :: Demo login applicationSomkiat Puisungnoen
 
Spring cheat sheet
Spring cheat sheetSpring cheat sheet
Spring cheat sheetMark Papis
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
Spring Security
Spring SecuritySpring Security
Spring SecurityBoy Tech
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsStormpath
 
What Is Php
What Is PhpWhat Is Php
What Is PhpAVC
 
HTML-(workshop)7557.pptx
HTML-(workshop)7557.pptxHTML-(workshop)7557.pptx
HTML-(workshop)7557.pptxRaja980775
 
PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?Sam Thomas
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksEndranNL
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 

Was ist angesagt? (20)

Robot Framework :: Demo login application
Robot Framework :: Demo login applicationRobot Framework :: Demo login application
Robot Framework :: Demo login application
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring cheat sheet
Spring cheat sheetSpring cheat sheet
Spring cheat sheet
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
Html
HtmlHtml
Html
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
HTML-(workshop)7557.pptx
HTML-(workshop)7557.pptxHTML-(workshop)7557.pptx
HTML-(workshop)7557.pptx
 
PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?
 
Basic HTML
Basic HTMLBasic HTML
Basic HTML
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Html basics
Html basicsHtml basics
Html basics
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 

Ähnlich wie Usage Note of SWIG for PHP

Setting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntuSetting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntukesavan N B
 
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Fabrice Bernhard
 
DevNet Associate : Python introduction
DevNet Associate : Python introductionDevNet Associate : Python introduction
DevNet Associate : Python introductionJoel W. King
 
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSH
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSHTame Your Build And Deployment Process With Hudson, PHPUnit, and SSH
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSHDavid Stockton
 
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agentsPVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agentsAndrey Karpov
 
Drupal Continuous Integration with Jenkins - Deploy
Drupal Continuous Integration with Jenkins - DeployDrupal Continuous Integration with Jenkins - Deploy
Drupal Continuous Integration with Jenkins - DeployJohn Smith
 
R server and spark
R server and sparkR server and spark
R server and sparkBAINIDA
 
PVS-Studio in the Clouds: Travis CI
PVS-Studio in the Clouds: Travis CIPVS-Studio in the Clouds: Travis CI
PVS-Studio in the Clouds: Travis CIAndrey Karpov
 
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Pantheon
 
Azure DevOps Extensions
Azure DevOps ExtensionsAzure DevOps Extensions
Azure DevOps ExtensionsChristian Waha
 
Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson Dev_Events
 
Workshop MSF4J - Getting Started with Microservices and Java
Workshop MSF4J - Getting Started with Microservices and JavaWorkshop MSF4J - Getting Started with Microservices and Java
Workshop MSF4J - Getting Started with Microservices and JavaEdgar Silva
 
Jump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & GithubJump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & Githubhubx
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014biicode
 
OpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in PythonOpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in PythonCodeOps Technologies LLP
 

Ähnlich wie Usage Note of SWIG for PHP (20)

Setting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntuSetting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntu
 
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
 
DevNet Associate : Python introduction
DevNet Associate : Python introductionDevNet Associate : Python introduction
DevNet Associate : Python introduction
 
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSH
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSHTame Your Build And Deployment Process With Hudson, PHPUnit, and SSH
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSH
 
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agentsPVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
 
Drupal Continuous Integration with Jenkins - Deploy
Drupal Continuous Integration with Jenkins - DeployDrupal Continuous Integration with Jenkins - Deploy
Drupal Continuous Integration with Jenkins - Deploy
 
R server and spark
R server and sparkR server and spark
R server and spark
 
Docker Starter Pack
Docker Starter PackDocker Starter Pack
Docker Starter Pack
 
PVS-Studio in the Clouds: Travis CI
PVS-Studio in the Clouds: Travis CIPVS-Studio in the Clouds: Travis CI
PVS-Studio in the Clouds: Travis CI
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
 
Azure DevOps Extensions
Azure DevOps ExtensionsAzure DevOps Extensions
Azure DevOps Extensions
 
Deployment automation
Deployment automationDeployment automation
Deployment automation
 
Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson
 
Workshop MSF4J - Getting Started with Microservices and Java
Workshop MSF4J - Getting Started with Microservices and JavaWorkshop MSF4J - Getting Started with Microservices and Java
Workshop MSF4J - Getting Started with Microservices and Java
 
Apache Web Server Setup 2
Apache Web Server Setup 2Apache Web Server Setup 2
Apache Web Server Setup 2
 
Jump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & GithubJump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & Github
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014
 
OpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in PythonOpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in Python
 
InfoPay v5 Developers Manual
InfoPay v5 Developers ManualInfoPay v5 Developers Manual
InfoPay v5 Developers Manual
 

Mehr von William Lee

Usage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP LanguagesUsage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP LanguagesWilliam Lee
 
Usage Note of Qt ODBC Database Access on Linux
Usage Note of Qt ODBC Database Access on LinuxUsage Note of Qt ODBC Database Access on Linux
Usage Note of Qt ODBC Database Access on LinuxWilliam Lee
 
Upgrade GCC & Install Qt 5.4 on CentOS 6.5
Upgrade GCC & Install Qt 5.4 on CentOS 6.5 Upgrade GCC & Install Qt 5.4 on CentOS 6.5
Upgrade GCC & Install Qt 5.4 on CentOS 6.5 William Lee
 
Usage Notes of The Bro 2.2 / 2.3
Usage Notes of The Bro 2.2 / 2.3Usage Notes of The Bro 2.2 / 2.3
Usage Notes of The Bro 2.2 / 2.3William Lee
 
Viewing Android Source Files in Eclipse (Chinese)
Viewing Android Source Files in Eclipse  (Chinese)Viewing Android Source Files in Eclipse  (Chinese)
Viewing Android Source Files in Eclipse (Chinese)William Lee
 
Usage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency WalkerUsage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency WalkerWilliam Lee
 
Usage Note of PlayCap
Usage Note of PlayCapUsage Note of PlayCap
Usage Note of PlayCapWilliam Lee
 
Qt4 App - Sliding Window
Qt4 App - Sliding WindowQt4 App - Sliding Window
Qt4 App - Sliding WindowWilliam Lee
 
GTK+ 2.0 App - Desktop App Chooser
GTK+ 2.0 App - Desktop App ChooserGTK+ 2.0 App - Desktop App Chooser
GTK+ 2.0 App - Desktop App ChooserWilliam Lee
 
GTK+ 2.0 App - Icon Chooser
GTK+ 2.0 App - Icon ChooserGTK+ 2.0 App - Icon Chooser
GTK+ 2.0 App - Icon ChooserWilliam Lee
 
Note of CGI and ASP
Note of CGI and ASPNote of CGI and ASP
Note of CGI and ASPWilliam Lee
 
Moblin2 - Window Manager(Mutter) Plugin
Moblin2 - Window Manager(Mutter) PluginMoblin2 - Window Manager(Mutter) Plugin
Moblin2 - Window Manager(Mutter) PluginWilliam Lee
 
Asterisk (IP-PBX) CDR Log Rotation
Asterisk (IP-PBX) CDR Log RotationAsterisk (IP-PBX) CDR Log Rotation
Asterisk (IP-PBX) CDR Log RotationWilliam Lee
 
L.A.M.P Installation Note --- CentOS 6.5
L.A.M.P Installation Note --- CentOS 6.5L.A.M.P Installation Note --- CentOS 6.5
L.A.M.P Installation Note --- CentOS 6.5William Lee
 
C Program Runs on Wrong Target Platform(CPU Architecture)
C Program Runs on Wrong Target Platform(CPU Architecture)C Program Runs on Wrong Target Platform(CPU Architecture)
C Program Runs on Wrong Target Platform(CPU Architecture)William Lee
 
Internationalization(i18n) of Web Page
Internationalization(i18n) of Web PageInternationalization(i18n) of Web Page
Internationalization(i18n) of Web PageWilliam Lee
 
Notes for SQLite3 Usage
Notes for SQLite3 UsageNotes for SQLite3 Usage
Notes for SQLite3 UsageWilliam Lee
 
Cygwin Install How-To (Chinese)
Cygwin Install How-To (Chinese)Cygwin Install How-To (Chinese)
Cygwin Install How-To (Chinese)William Lee
 
Android Storage - StorageManager & OBB
Android Storage - StorageManager & OBBAndroid Storage - StorageManager & OBB
Android Storage - StorageManager & OBBWilliam Lee
 

Mehr von William Lee (20)

Usage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP LanguagesUsage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP Languages
 
Usage Note of Qt ODBC Database Access on Linux
Usage Note of Qt ODBC Database Access on LinuxUsage Note of Qt ODBC Database Access on Linux
Usage Note of Qt ODBC Database Access on Linux
 
Upgrade GCC & Install Qt 5.4 on CentOS 6.5
Upgrade GCC & Install Qt 5.4 on CentOS 6.5 Upgrade GCC & Install Qt 5.4 on CentOS 6.5
Upgrade GCC & Install Qt 5.4 on CentOS 6.5
 
Usage Notes of The Bro 2.2 / 2.3
Usage Notes of The Bro 2.2 / 2.3Usage Notes of The Bro 2.2 / 2.3
Usage Notes of The Bro 2.2 / 2.3
 
Viewing Android Source Files in Eclipse (Chinese)
Viewing Android Source Files in Eclipse  (Chinese)Viewing Android Source Files in Eclipse  (Chinese)
Viewing Android Source Files in Eclipse (Chinese)
 
Usage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency WalkerUsage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency Walker
 
Usage Note of PlayCap
Usage Note of PlayCapUsage Note of PlayCap
Usage Note of PlayCap
 
Qt4 App - Sliding Window
Qt4 App - Sliding WindowQt4 App - Sliding Window
Qt4 App - Sliding Window
 
GTK+ 2.0 App - Desktop App Chooser
GTK+ 2.0 App - Desktop App ChooserGTK+ 2.0 App - Desktop App Chooser
GTK+ 2.0 App - Desktop App Chooser
 
GTK+ 2.0 App - Icon Chooser
GTK+ 2.0 App - Icon ChooserGTK+ 2.0 App - Icon Chooser
GTK+ 2.0 App - Icon Chooser
 
Note of CGI and ASP
Note of CGI and ASPNote of CGI and ASP
Note of CGI and ASP
 
Moblin2 - Window Manager(Mutter) Plugin
Moblin2 - Window Manager(Mutter) PluginMoblin2 - Window Manager(Mutter) Plugin
Moblin2 - Window Manager(Mutter) Plugin
 
MGCP Overview
MGCP OverviewMGCP Overview
MGCP Overview
 
Asterisk (IP-PBX) CDR Log Rotation
Asterisk (IP-PBX) CDR Log RotationAsterisk (IP-PBX) CDR Log Rotation
Asterisk (IP-PBX) CDR Log Rotation
 
L.A.M.P Installation Note --- CentOS 6.5
L.A.M.P Installation Note --- CentOS 6.5L.A.M.P Installation Note --- CentOS 6.5
L.A.M.P Installation Note --- CentOS 6.5
 
C Program Runs on Wrong Target Platform(CPU Architecture)
C Program Runs on Wrong Target Platform(CPU Architecture)C Program Runs on Wrong Target Platform(CPU Architecture)
C Program Runs on Wrong Target Platform(CPU Architecture)
 
Internationalization(i18n) of Web Page
Internationalization(i18n) of Web PageInternationalization(i18n) of Web Page
Internationalization(i18n) of Web Page
 
Notes for SQLite3 Usage
Notes for SQLite3 UsageNotes for SQLite3 Usage
Notes for SQLite3 Usage
 
Cygwin Install How-To (Chinese)
Cygwin Install How-To (Chinese)Cygwin Install How-To (Chinese)
Cygwin Install How-To (Chinese)
 
Android Storage - StorageManager & OBB
Android Storage - StorageManager & OBBAndroid Storage - StorageManager & OBB
Android Storage - StorageManager & OBB
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Usage Note of SWIG for PHP

  • 1. Usage Note Of SWIG for PHP William.L wiliwe@gmail.com 2015-08-20
  • 2. Index What is SWIG? ..................................................................................................................................................... 3 Install SWIG Tool & Library............................................................................................................................... 4 SWIG for PHP....................................................................................................................................................... 6 Generate and Install PHP Extension................................................................................................................... 7 Use PHP Extension.............................................................................................................................................. 18
  • 3. What is SWIG? SWIG, Simplified Wrapper and Interface Generator, is a software development tool for building scripting language interfaces to C and C++ programs. It is a kind of interface definition/description language (IDL). Originally developed in 1995, SWIG was first used by scientists in the Theoretical Physics Division at Los Alamos National Laboratory for building user interfaces to simulation codes running on the Connection Machine 5 supercomputer. SWIG was originally designed to make it extremely easy for scientists and engineers to build extensible scientific software without having to get a degree in software engineering. It simplifies the task of interfacing different languages to C and C++ programs by largely automating the task of language integration--allowing developers and users to focus on more important problems. In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates the wrappers needed to access those declarations from other languages including Perl, PHP, Python, Tcl, Ruby, Guile, and Java. SWIG normally requires no modifications to existing code and can often be used to build a usable interface in only a few minutes. SWIG official site: * http://swig.org/ SWIG documentation and tutorial: * http://swig.org/doc.html * http://swig.org/tutorial.html Download SWIG source archive for different operating system platforms: * http://sourceforge.net/projects/swig/files/ Example codes for this documentation could be downloaded from the GitHub: https://github.com/wiliwe/swig-php-example
  • 4. Install SWIG Tool & Library The environment used in this document: * Linux CentOS 6.5 64-bit (could be updated to 6.6 or 6.7) * GCC C/C++ compiler v4.9.0 (which support C++11 and C++14 standards) * SWIG v3.0.7 (released on 2015-08-03) (Note that in console/terminal, type “swig -version”, it will show v1.3.40) * PHP v5.3.3 * Qt Creator v3.3.1 IDE tool Before installing the SWIG v3.0.7, please remove the old built-in SWIG from CentOS 6.5: $ su (change to root) # yum erase swig Build & Install SWIG tool and libraries The SWIG tool/library installation guide is described in “Installation” section of chapter 1, “Preface.” 1) Donwload the SWIG v3.0.7 source archive for Unix/Linux, swig-3.0.7.tar.gz, from the site: http://sourceforge.net/projects/swig/files/swig/swig-3.0.7/
  • 5. 2) Unpack swig-3.0.7.tar.gz to generate a folder named “swig-3.0.7”. 3) Enter the folder “swig-3.0.7” and run below commands to build and install SWIG tool and library: $ ./configure --prefix=/usr --libdir=/usr/lib64 $ make $ su (change to root) # make install By default SWIG installs itself in “/usr/local”. The installation path could be found in the file config.log which is under the directory “swig-3.0.7”. In config.log , search “prefix=” and “libdir=” variable assignments and you could see the installation path. After installing, run “swig -version” to verify the version of the SWIG is what we set. 4) It could use command “swig -swiglib” tool to find out where SWIG thinks its library is located (be sure SWIG tool and library are installed properly before running this command).
  • 6. SWIG for PHP For PHP scripting language, SWIG generates PHP Extensions (or called modules) for gluing C or C++ codes. PHP extension is as a dynamically loaded library: in MSFT Windows, it is DLL(.dll) ; in Unix/Linux, it is SO(.so); in Apple Mac OS X, it is DYLIB(.dylib). The location of PHP built-in modules could be found from the result of execution of PHP phpinfo() function: In SWIG documentaiton 3.0 (http://swig.org/Doc3.0/index.html), chapter 4 explain the relationship between scripting language (pythong, PHP, perl, etc) and C/C++ languages.
  • 7. Generate and Install PHP Extension Basic steps of using SWIG are as below: 1) Write a SWIG interface file describing the interface name and its parameter. The interface files usually end with “.i” extension name which stands for “interface.” Below snapshots are examples for SWIG interface writing. It could declare all interfaces name in the interface file or use a header to contain it and include this header file into the interface file. <Non Header Way> < Header way> 2) Use SWIG tool(swig) with the written interface file as input to generate files for building out extension/module file of target language. Below commands are for building out PHP extensions from C and C++, you could put then into a Make file and make it. Remember that it MUST run “swig” tool to generate C or C++ wrapping source and header files for the generation of PHP extension file as the FIRST step. For generating PHP extension, it needs PHP development library header, so run below commands to install it: $ su (change to root) # yum install php-devel.x86_64 <For C> swig -php swigphp.i (replace “swigphp.i” with your SWIG interface file name) gcc `php-config --includes` -fpic -c swigphp_wrap.c swigphp.c gcc -shared swigphp_wrap.o helloswig.o -o swigphp.so
  • 8. Running “swig” tool for C++ will generate three files: * swigphp_wrap.c * php_swigphp.h * swigphp.php <For C++> swig -c++ -php swigphp.i (replace “swigphp.i” with your SWIG interface file name) g++ `php-config --includes` -fpic -c swigphp_wrap.cpp swigphp.cpp g++ -shared swigphp_wrap.o swigphp.o -o swigphp.so Running “swig” tool for C++ will generate three files: * swigphp_wrap.cpp * php_swigphp.h * swigphp.php Below snapshots show an example of generation and compilation of a PHP extension, helloswigc.so. Besides command line way, it could use Qt Creator IDE and QMake to build out PHP extension. The Qt Creator project setup steps are show below. The needed C or C++ source files are needed to be generated through “swig” tool in advance. 1) Create a whole new Qt project by clicking these items: “Library” -> “C++ Library”
  • 9.
  • 10.
  • 11. In project window, remove the Qt Creator generated files. Add C or C++ source files generated by “swig” tool into Qt Creator project. * php_SWIG-Module-Name.h * SWIG-Module-Name _wrap.c (for C) or SWIG-Module-Name _wrap.cpp (for C++).
  • 12. 5) In Qt PRO file, change the value of TARGET variable for output file name you want.
  • 13. 6) In Qt PRO file, add below line for searching PHP zend.h file when building. QMAKE_CXXFLAGS += `php-config --includes` Also, add C++10 standard supporting flag. QMAKE_CXXFLAGS += -std=c++0x 7) Uncheck “Projects-> Build & Run -> Shadow build“ for “Debug” and “Release”. 8) Start to build by clicking “Build” button (a hammer icon) on IDE’s side panel. 9) After building out SWIG PHP extension SO file successfully, it will generate the file "libhelloswigc.so.1.0.0" whose version number may not be “1.0.0”, it is up to your setting. Change extension file name from " libhelloswigc.so.1.0.0" to "helloswigc.so". Install PHP Extension Edit /etc/php.ini , in "Dynamic Extensions" section, add this line: extension = helloswigc.so Drop down to change to Debug or Release.
  • 14. It could add more than one lines of “extension=” for multiple PHP extension loading. Save /etc/php.ini and use “php -m” command to verify if it could load new assigned PHP extension successfully.
  • 15. If a PHP extension file specified in php.ini does not exist under PHP extension folder, it will show below error message: Finally, restart Apache through the commands: $ su (change to root) # service httpd restart Note that the PHP configuration file, php.ini, may locate in other folder. You could find it through put a PHP page(file name ends with ".php") under /var/www/html folder and the page's contents are as below: In Web browser, to browse this PHP page, if it could be run successfully, it will show information about PHP. <?php phpinfo(); ?> Note When running “php -m” If it could not find one or more needed libraries the PHP extension depends on, it will show error message that tell you which library could not be found.
  • 16. Look at the entry having the string "Loaded Configuration File" , it shows the actual path to php.ini file. Run below commands in root to put "helloswigc.so" file to PHP module folder. $ su (change to root) # cp ./helloswigc.so `php-config --extension-dir` , where `php-config --extension-dir` option will output the path to PHP module folder. Note <1> When building C++ file, it MUST use g++ or c++ instead of gcc compiler, or it will happen error when loading PHP extension/module that it will say it could not find name mangling/decoration symbol as below snapshot.
  • 17. <2> For earlier version of SWIG, if the version of PHP library for building PHP extension is not the same as the one you will run on, it might show this error message when running “php -m” command: “Unable to initialize module” , see below sites for more information: * http://php.net/manual/en/solr.installation.php * http://stackoverflow.com/questions/2394532/apache-is-unable-to-initialize-module-because-of-modules-and-phps-api-dont * http://stackoverflow.com/questions/3130910/php-warning-php-startup-unable-to-initialize-module
  • 18. Use PHP Extension Write a PHP file including “swig” tool generated PHP file and call the interface specified in SWIG interface file. Below snapshot shows an example that helloswigc_test.php includes helloswigc.php which was generated by “swig” tool. In Web browser, locate to helloswigc_test.php, if anything is okay, it could show the result what you want. It could use “php” tool to run PHP page. For example: $ php -c . /var/www/html/ helloswigc_test.php Note If one or more PHP extensions contain more than one identical class names or macro without using namespace to isolate it, it will cause fatal errors and let Apache Web server crash, it will not boot successfully until the class name confilict issue is remove.