PageRenderTime 56ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/Doc/Manual/Php.html

#
HTML | 1211 lines | 908 code | 233 blank | 70 comment | 0 complexity | b27706edc56d21a0657cd597db771ce2 MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <!-- Hand crafted HTML -->
  3. <html>
  4. <head>
  5. <title>SWIG and PHP</title>
  6. <link rel="stylesheet" type="text/css" href="style.css">
  7. </head>
  8. <body bgcolor="#ffffff">
  9. <H1><a name="Php"></a>32 SWIG and PHP</H1>
  10. <!-- INDEX -->
  11. <div class="sectiontoc">
  12. <ul>
  13. <li><a href="#Php_nn1">Generating PHP Extensions</a>
  14. <ul>
  15. <li><a href="#Php_nn1_1">Building a loadable extension</a>
  16. <li><a href="#Php_nn1_3">Using PHP Extensions</a>
  17. </ul>
  18. <li><a href="#Php_nn2">Basic PHP interface</a>
  19. <ul>
  20. <li><a href="#Php_nn2_1">Constants</a>
  21. <li><a href="#Php_nn2_2">Global Variables</a>
  22. <li><a href="#Php_nn2_3">Functions</a>
  23. <li><a href="#Php_nn2_4">Overloading</a>
  24. <li><a href="#Php_nn2_5">Pointers and References</a>
  25. <li><a href="#Php_nn2_6">Structures and C++ classes</a>
  26. <ul>
  27. <li><a href="#Php_nn2_6_1">Using <tt>-noproxy</tt></a>
  28. <li><a href="#Php_nn2_6_2">Constructors and Destructors</a>
  29. <li><a href="#Php_nn2_6_3">Static Member Variables</a>
  30. <li><a href="#Php_nn2_6_4">Static Member Functions</a>
  31. </ul>
  32. <li><a href="#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</a>
  33. </ul>
  34. <li><a href="#Php_nn3">Cross language polymorphism</a>
  35. <ul>
  36. <li><a href="#Php_nn3_1">Enabling directors</a>
  37. <li><a href="#Php_nn3_2">Director classes</a>
  38. <li><a href="#Php_nn3_3">Ownership and object destruction</a>
  39. <li><a href="#Php_nn3_4">Exception unrolling</a>
  40. <li><a href="#Php_nn3_5">Overhead and code bloat</a>
  41. <li><a href="#Php_nn3_6">Typemaps</a>
  42. <li><a href="#Php_nn3_7">Miscellaneous</a>
  43. </ul>
  44. </ul>
  45. </div>
  46. <!-- INDEX -->
  47. <p>
  48. SWIG supports generating wrappers for PHP5. Support for PHP4 was removed
  49. in SWIG 1.3.37. The PHP developers are no longer making new PHP4 releases,
  50. and won't even be patching critical security issues after 2008-08-08, so it
  51. doesn't make much sense for SWIG to continue to support PHP4 now. If you
  52. really need to continue to use PHP4, just stick with SWIG 1.3.36.
  53. </p>
  54. <p>
  55. Currently any PHP5 release should work, but we don't regularly test with
  56. PHP &lt; 5.3.
  57. </p>
  58. <p>
  59. In this chapter, we discuss SWIG's support of PHP. The PHP module
  60. was extensively rewritten in release 1.3.26, and support for generating
  61. OO wrappers for PHP5 was added in 1.3.30. The PHP module now supports most
  62. of the features available in some of the other languages.
  63. </p>
  64. <p>
  65. In order to use this module, you will need to have a copy of the PHP5
  66. include files to compile the SWIG generated files. If you installed
  67. PHP from a binary package, you may need to install a "php-dev" or "php-devel"
  68. package for these to be installed. You can find out where these files are
  69. by running <tt>php-config --includes</tt>. To use the built PHP module you
  70. will need either the php binary or the Apache php module. If you want to build
  71. your extension into php directly, you will need the complete PHP source tree
  72. available.
  73. </p>
  74. <H2><a name="Php_nn1"></a>32.1 Generating PHP Extensions</H2>
  75. <p>
  76. To build a PHP extension, run swig using the <tt>-php</tt> option as
  77. follows:
  78. </p>
  79. <div class="code"><pre>
  80. swig -php example.i
  81. </pre></div>
  82. <p>
  83. This will produce 3 files example_wrap.c, php_example.h and
  84. example.php. The first file, <tt>example_wrap.c</tt> contains all of
  85. the C code needed to build a PHP extension. The second file,
  86. <tt>php_example.h</tt> contains the header information needed if
  87. you wish to statically link the extension into the php interpreter.
  88. The third file,
  89. <tt>example.php</tt> can be included by PHP scripts. It attempts to
  90. dynamically load the extension and contains extra php code specified
  91. in the interface file. If wrapping C++ code with PHP classes, it will
  92. also contain PHP5 class wrappers.
  93. </p>
  94. <p>
  95. SWIG can generate PHP extensions from C++ libraries as well when
  96. given the <tt>-c++</tt> option. The support for C++ is discussed in
  97. more detail in <a href="#Php_nn2_6">section 27.2.6</a>.
  98. </p>
  99. <p>
  100. The usual (and recommended) way is to build the extension as a separate
  101. dynamically loaded module (which is supported by all modern operating
  102. systems). You can then specify that this be loaded
  103. automatically in <tt>php.ini</tt> or load it explicitly for any script which
  104. needs it.
  105. </p>
  106. <p>
  107. It is also possible to rebuild PHP from source so that your module is
  108. statically linked into the php executable/library. This is a lot more
  109. work, and also requires a full rebuild of PHP to update your module,
  110. and it doesn't play nicely with package system. We don't recommend
  111. this approach, or provide explicit support for it.
  112. </p>
  113. <H3><a name="Php_nn1_1"></a>32.1.1 Building a loadable extension</H3>
  114. <p>
  115. To build your module as a dynamically loadable extension, use compilation
  116. commands like these (if you aren't using GCC, the commands will be different,
  117. and there may be some variation between platforms - these commands should at
  118. least work for Linux though):
  119. </p>
  120. <div class="code"><pre>
  121. gcc `php-config --includes` -fpic -c example_wrap.c
  122. gcc -shared example_wrap.o -o example.so
  123. </pre></div>
  124. <H3><a name="Php_nn1_3"></a>32.1.2 Using PHP Extensions</H3>
  125. <p>
  126. To test the extension from a PHP script, you need to load it first. You
  127. can load it for every script by adding this line the <tt>[PHP]</tt> section of
  128. <tt>php.ini</tt>:
  129. </p>
  130. <div class="code"><pre>
  131. extension=/path/to/modulename.so
  132. </pre></div>
  133. <p>
  134. Alternatively, you can load it explicitly only for scripts which need it
  135. by adding this line:
  136. </p>
  137. <div class="code"><pre>
  138. dl("/path/to/modulename.so"); // Load the module
  139. </pre></div>
  140. <p>
  141. to the start of each PHP file. SWIG also generates a php module, which
  142. attempts to do the <tt>dl()</tt> call for you:
  143. </p>
  144. <div class="code"><pre>
  145. include("example.php");
  146. </pre></div>
  147. <H2><a name="Php_nn2"></a>32.2 Basic PHP interface</H2>
  148. <p>
  149. It is important to understand that PHP uses a single global namespace
  150. into which all symbols from extension modules are loaded. It is quite
  151. possible for names of symbols in one extension module to clash with
  152. other symbols unless care is taken to <tt>%rename</tt> them. At present
  153. SWIG doesn't have support for the namespace feature added in PHP 5.3.
  154. </p>
  155. <H3><a name="Php_nn2_1"></a>32.2.1 Constants</H3>
  156. <p>
  157. These work in much the same way as in C/C++. Constants can be defined
  158. by using either the normal C pre-processor declarations, or the
  159. <tt>%constant</tt> SWIG directive. These will then be available from
  160. your PHP script as a PHP constant, (i.e. no dollar sign is needed to
  161. access them.) For example, with a swig interface file like this,
  162. </p>
  163. <div class="code"><pre>
  164. %module example
  165. #define PI 3.14159
  166. %constant int E = 2.71828
  167. </pre>
  168. </div>
  169. <p>
  170. you can access the constants in your PHP script like this,
  171. </p>
  172. <div class="code"><pre>
  173. include("example.php");
  174. echo "PI = " . PI . "\n";
  175. echo "E = " . E . "\n";
  176. </pre>
  177. </div>
  178. <p>
  179. There's one peculiarity of how constants work in PHP which it is useful
  180. to note (this is not specific to SWIG though) - if you try to use an undeclared
  181. constant, PHP will issue a warning and then expand the constant to a string
  182. version of the constant's name. The warning will often be missed though as
  183. if you're using PHP in a webserver, it will probably end up in error.log or
  184. similar.
  185. </p>
  186. <p>
  187. For example,
  188. </p>
  189. <div class="code"><pre>
  190. %module example
  191. #define EASY_TO_MISPELL 0
  192. </pre>
  193. </div>
  194. <p>
  195. accessed incorrectly in PHP,
  196. </p>
  197. <div class="code">
  198. <pre>
  199. include("example.php");
  200. if(EASY_TO_MISPEL) {
  201. ....
  202. } else {
  203. ....
  204. }
  205. </pre>
  206. </div>
  207. <p>
  208. The mis-spelled constant will become the string 'EASY_TO_MISPEL', which
  209. is treated as true by the if test, when the value of the intended constant
  210. would be treated as false!
  211. </p>
  212. <H3><a name="Php_nn2_2"></a>32.2.2 Global Variables</H3>
  213. <p>
  214. Because PHP does not provide a mechanism to intercept access and
  215. assignment of global variables, global variables are supported through
  216. the use of automatically generated accessor functions.
  217. </p>
  218. <div class="code"><pre>
  219. %module example;
  220. %inline %{
  221. double seki = 2;
  222. void print_seki() {
  223. zend_printf("seki is now %f\n",seki);
  224. }
  225. %}
  226. </pre></div>
  227. <p>
  228. is accessed as follows:
  229. </p>
  230. <div class="code"><pre>
  231. include("example.php");
  232. print seki_get();
  233. seki_set( seki_get() * 2); # The C variable is now 4.
  234. print seki_get();
  235. </pre></div>
  236. <p>
  237. SWIG supports global variables of all C datatypes including pointers
  238. and complex objects. Additional types can be supported by using the
  239. <tt>varinit</tt> typemap.
  240. </p>
  241. <p>
  242. SWIG honors the <tt>%immutable</tt> modifier by not generating code
  243. for the <tt>_set</tt> method. This provides read-only access to the
  244. variable from the php script. Attempting to access the <tt>_set</tt>
  245. method will result in a php fatal error because the function is
  246. undefined.
  247. </p>
  248. <p>
  249. At this time SWIG does not support custom accessor methods.
  250. </p>
  251. <H3><a name="Php_nn2_3"></a>32.2.3 Functions</H3>
  252. <p>
  253. C functions are converted into PHP functions. Default/optional arguments are
  254. also allowed. An interface file like this :
  255. </p>
  256. <div class="code"><pre>
  257. %module example
  258. int foo(int a);
  259. double bar(double, double b = 3.0);
  260. ...
  261. </pre></div>
  262. <p>
  263. Will be accessed in PHP like this :
  264. </p>
  265. <div class="code"><pre>
  266. include("example.php");
  267. $a = foo(2);
  268. $b = bar(3.5, -1.5);
  269. $c = bar(3.5); # Use default argument for 2nd parameter
  270. </pre></div>
  271. <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
  272. <p>
  273. Because PHP is a dynamically typed language, the default typemaps
  274. used for simple types will attempt to coerce the arguments into the appropriate type. That is the following invocations are equivalent:
  275. </p>
  276. <div class="code"><pre>
  277. $a = foo(2);
  278. $a = foo("2");
  279. $a = foo(2.0);
  280. </pre></div>
  281. <p>
  282. Functions are invoked using pass by value semantics like all of PHP.
  283. This means the conversion which automatically takes place when
  284. invoking a swig wrapped method does not change the native type of the
  285. argument variable.
  286. </p>
  287. <div class="code"><pre>
  288. $s = "2 A string representing two";
  289. $a = foo($s); # invokes 'foo(2)';
  290. print $s; # The value of $s was not changed.
  291. </pre></div>
  292. -->
  293. <H3><a name="Php_nn2_4"></a>32.2.4 Overloading</H3>
  294. <p>
  295. Although PHP does not support overloading functions natively, swig
  296. will generate dispatch functions which will use <tt>%typecheck</tt>
  297. typemaps to allow overloading. This dispatch function's operation and
  298. precedence is described in <a
  299. href="SWIGPlus.html#SWIGPlus_overloaded_methods">Wrapping
  300. Overloaded Functions and Methods</a>.
  301. </p>
  302. <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
  303. <p>
  304. Because PHP is a dynamically typed language, simple values can be
  305. silently converted from one type to another. For example, integers,
  306. doubles and strings silently convert to each other depending on
  307. context. This situation make overloading slightly problematic because
  308. given the following function:
  309. </p>
  310. <div class="code"><pre>
  311. void doit( int i );
  312. void doit( double i );
  313. </pre></div>
  314. <p>
  315. it is questionable which to invoke when <tt>doit("2");</tt> is used in
  316. PHP. The string <tt>"2"</tt> simultaneously represents the integer
  317. <tt>2</tt> and the double <tt>2.0</tt>.
  318. </p>
  319. <p>
  320. In order to provide the most natural experience to PHP programmers,
  321. the default <tt>%typecheck</tt> implemented in <tt>php.swg</tt>
  322. allows any simple type (integer, double, string) in PHP to be used for
  323. any simple C type (int, double, char *). The function selected then
  324. depends only on the argument type precedence defined by SWIG.
  325. </p>
  326. <p>
  327. It should be noted that <tt>SWIGTYPE</tt> references and pointers will
  328. not be silently converted. So these two functions:
  329. </p>
  330. <div class="code"><pre>
  331. void doit( const Vector &amp; );
  332. void doit( int i );
  333. </pre></div>
  334. <p>
  335. Cause less confusion and <tt>doit("2");</tt> will invoke the function
  336. taking the integer argument.
  337. </p>
  338. -->
  339. <H3><a name="Php_nn2_5"></a>32.2.5 Pointers and References</H3>
  340. <p>
  341. Pointers to C/C++ objects are represented
  342. as PHP resources, rather like MySQL connection handles.
  343. </p>
  344. <p>
  345. There are multiple ways to wrap pointers to simple types. Given the
  346. following C method:
  347. </p>
  348. <div class="code"><pre>
  349. void add( int *in1, int *in2, int *result);
  350. </pre></div>
  351. <p>
  352. One can include <b>cpointer.i</b> to generate PHP wrappers to <tt>int
  353. *</tt>.
  354. </p>
  355. <div class="code"><pre>
  356. %module example
  357. %include "cpointer.i"
  358. %pointer_functions(int,intp)
  359. void add( int *in1, int *in2, int *result);
  360. </pre></div>
  361. <p>
  362. This will result in the following usage in PHP:
  363. </p>
  364. <div class="code"><pre>
  365. &lt;?php
  366. include("example.php");
  367. $in1=copy_intp(3);
  368. $in2=copy_intp(5);
  369. $result=new_intp();
  370. add( $in1, $in2, $result );
  371. echo "The sum " . intp_value($in1) . " + " . intp_value($in2) . " = " . intp_value( $result) . "\n";
  372. ?&gt;
  373. </pre></div>
  374. <p>
  375. An alternative would be to use the include <b>typemaps.i</b> which
  376. defines named typemaps for INPUT, OUTPUT and INOUT variables. One
  377. needs to either <tt>%apply</tt> the appropriate typemap or adjust the
  378. parameter names as appropriate.
  379. </p>
  380. <div class="code"><pre>
  381. %module example
  382. %include "typemaps.i"
  383. void add( int *INPUT, int *INPUT, int *OUTPUT);
  384. </pre></div>
  385. <p>
  386. This will result in the following usage in PHP:
  387. </p>
  388. <div class="code"><pre>
  389. &lt;?php
  390. include("example.php");
  391. $in1 = 3;
  392. $in2 = 5;
  393. $result= add($in1,$in2); # Note using variables for the input is unnecessary.
  394. echo "The sum $in1 + $in2 = $result\n";
  395. ?&gt;
  396. </pre></div>
  397. <p>
  398. Because PHP has a native concept of reference, it may seem more natural
  399. to the PHP developer to use references to pass pointers. To enable
  400. this, one needs to include <b>phppointers.i</b> which defines the
  401. named typemap REFERENCE.
  402. </p>
  403. <div class="code"><pre>
  404. %module example
  405. %include "phppointers.i"
  406. void add( int *REF, int *REF, int *REF);
  407. </pre></div>
  408. <p>
  409. This will result in the following usage in PHP:
  410. </p>
  411. <div class="code"><pre>
  412. &lt;?php
  413. include("example.php");
  414. $in1 = 3;
  415. $in2 = 5;
  416. $result = 0;
  417. add(&amp;$in1,&amp;$in2,&amp;$result);
  418. echo "The sum $in1 + $in2 = $result\n";
  419. ?&gt;
  420. </pre></div>
  421. <p>
  422. It is important to note that a php variable which is NULL when passed
  423. by reference would end up passing a NULL pointer into the function.
  424. In PHP, an unassigned variable (i.e. where the first reference to the
  425. variable is not an assignment) is
  426. NULL. In the above example, if any of the three variables had not
  427. been assigned, a NULL pointer would have been passed into
  428. <tt>add</tt>. Depending on the implementation of the function, this
  429. may or may not be a good thing.
  430. </p>
  431. <p>
  432. We chose to allow passing NULL pointers into functions because that is
  433. sometimes required in C libraries. A NULL pointer can be created in
  434. PHP in a number of ways: by using <tt>unset</tt> on an existing
  435. variable, or assigning <tt>NULL</tt> to a variable.
  436. </p>
  437. <H3><a name="Php_nn2_6"></a>32.2.6 Structures and C++ classes</H3>
  438. <p>
  439. SWIG defaults to wrapping C++ structs and classes with PHP classes - this
  440. is done by generating a PHP wrapper script which defines proxy classes
  441. which calls a set of flat functions which actually wrap the C++ class.
  442. You can disable this wrapper layer by passing the command-line option
  443. "-noproxy" in which case you'll just get the flat functions.
  444. </p>
  445. <p>
  446. This interface file
  447. </p>
  448. <div class="code"><pre>
  449. %module vector
  450. class Vector {
  451. public:
  452. double x,y,z;
  453. Vector();
  454. ~Vector();
  455. double magnitude();
  456. };
  457. struct Complex {
  458. double re, im;
  459. };
  460. </pre></div>
  461. <p>
  462. Would be used in the following way from PHP5:
  463. </p>
  464. <div class="code"><pre>
  465. &lt;?php
  466. require "vector.php";
  467. $v = new Vector();
  468. $v-&gt;x = 3;
  469. $v-&gt;y = 4;
  470. $v-&gt;z = 5;
  471. echo "Magnitude of ($v-&gt;x,$v-&gt;y,$v-&gt;z) = " . $v-&gt;magnitude() . "\n";
  472. $v = NULL; # destructor called.
  473. $c = new Complex();
  474. $c-&gt;re = 0;
  475. $c-&gt;im = 0;
  476. # $c destructor called when $c goes out of scope.
  477. ?&gt;
  478. </pre></div>
  479. <p>
  480. Member variables and methods are accessed using the <tt>-&gt;</tt> operator.
  481. </p>
  482. <H4><a name="Php_nn2_6_1"></a>32.2.6.1 Using <tt>-noproxy</tt></H4>
  483. <p>
  484. The <tt>-noproxy</tt> option flattens the object structure and
  485. generates collections of named functions (these are the functions
  486. which the PHP5 class wrappers call). The above example results
  487. in the following PHP functions:
  488. </p>
  489. <div class="code"><pre>
  490. new_Vector();
  491. Vector_x_set($obj,$d);
  492. Vector_x_get($obj);
  493. Vector_y_set($obj,$d);
  494. Vector_y_get($obj);
  495. Vector_z_set($obj,$d);
  496. Vector_z_get($obj);
  497. Vector_magnitude($obj);
  498. new_Complex();
  499. Complex_re_set($obj,$d);
  500. Complex_re_get($obj);
  501. Complex_im_set($obj,$d);
  502. Complex_im_get($obj);
  503. </pre></div>
  504. <H4><a name="Php_nn2_6_2"></a>32.2.6.2 Constructors and Destructors</H4>
  505. <p>
  506. The constructor is called when <tt>new Object()</tt> (or
  507. <tt>new_Object()</tt> if using <tt>-noproxy</tt>) is used to create an
  508. instance of the object. If multiple constructors are defined for an
  509. object, function overloading will be used to determine which
  510. constructor to execute.
  511. </p>
  512. <p>
  513. Because PHP uses reference counting to manage resources, simple
  514. assignment of one variable to another such as:
  515. </p>
  516. <div class="code"><pre>
  517. $ref = $v;
  518. </pre></div>
  519. <p>
  520. causes the symbol <tt>$ref</tt> to refer to the same underlying object
  521. as <tt>$v</tt>. This does not result in a call to the C++ copy
  522. constructor or copy assignment operator.
  523. </p>
  524. <p>
  525. One can force execution of the copy constructor by using:
  526. </p>
  527. <div class="code"><pre>
  528. $o_copy = new Object($o);
  529. </pre></div>
  530. <p>
  531. Destructors are automatically called when all variables referencing
  532. the instance are reassigned or go out of scope. The destructor is not
  533. available to be called manually. To force a destructor to be called
  534. the programmer can either reassign the variable or call
  535. <tt>unset($v)</tt>
  536. </p>
  537. <H4><a name="Php_nn2_6_3"></a>32.2.6.3 Static Member Variables</H4>
  538. <p>
  539. Static member variables in C++ are not wrapped as such in PHP
  540. as it does not appear to be possible to intercept accesses to such variables.
  541. Therefore, static member variables are
  542. wrapped using a class function with the same name, which
  543. returns the current value of the class variable. For example
  544. </p>
  545. <div class="code"><pre>
  546. %module example
  547. class Ko {
  548. static int threats;
  549. };
  550. </pre></div>
  551. <p>
  552. would be accessed in PHP as,
  553. </p>
  554. <div class="code"><pre>
  555. include("example.php");
  556. echo "There has now been " . Ko::threats() . " threats\n";
  557. </pre></div>
  558. <p>
  559. To set the static member variable, pass the value as the argument to the class
  560. function, e.g.
  561. </p>
  562. <div class="code"><pre>
  563. Ko::threats(10);
  564. echo "There has now been " . Ko::threats() . " threats\n";
  565. </pre></div>
  566. <H4><a name="Php_nn2_6_4"></a>32.2.6.4 Static Member Functions</H4>
  567. <p>
  568. Static member functions are supported in PHP using the
  569. <tt>class::function()</tt> syntax. For example
  570. </p>
  571. <div class="code"><pre>
  572. %module example
  573. class Ko {
  574. static void threats();
  575. };
  576. </pre></div>
  577. would be executed in PHP as,
  578. <div class="code"><pre>
  579. include("example.php");
  580. Ko::threats();
  581. </pre></div>
  582. <H3><a name="Php_nn2_7"></a>32.2.7 PHP Pragmas, Startup and Shutdown code</H3>
  583. <p>
  584. To place PHP code in the generated "example.php" file one can use the
  585. <b>code</b> pragma. The code is inserted after loading the shared
  586. object.
  587. </p>
  588. <div class="code"><pre>
  589. %module example
  590. %pragma(php) code="
  591. # This code is inserted into example.php
  592. echo \"example.php execution\\n\";
  593. "
  594. </pre></div>
  595. <p>
  596. Results in the following in "example.php"
  597. </p>
  598. <div class="code"><pre>
  599. # This code is inserted into example.php
  600. echo "example.php execution\n";
  601. </pre></div>
  602. <p>
  603. The <b>include</b> pragma is a short cut to add include statements to
  604. the example.php file.
  605. </p>
  606. <div class="code"><pre>
  607. %module example
  608. %pragma(php) code="
  609. include \"include.php\";
  610. "
  611. %pragma(php) include="include.php" // equivalent.
  612. </pre></div>
  613. <p>
  614. The <b>phpinfo</b> pragma inserts code in the
  615. <tt>PHP_MINFO_FUNCTION</tt> which is called from PHP's
  616. phpinfo() function.
  617. </p>
  618. <div class="code"><pre>
  619. %module example;
  620. %pragma(php) phpinfo="
  621. zend_printf("An example of PHP support through SWIG\n");
  622. php_info_print_table_start();
  623. php_info_print_table_header(2, \"Directive\", \"Value\");
  624. php_info_print_table_row(2, \"Example support\", \"enabled\");
  625. php_info_print_table_end();
  626. "
  627. </pre></div>
  628. <p>
  629. To insert code into the <tt>PHP_MINIT_FUNCTION</tt>, one can use
  630. either <tt>%init</tt> or <tt>%minit</tt>.
  631. </p>
  632. <div class="code"><pre>
  633. %module example;
  634. %init {
  635. zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
  636. }
  637. %minit {
  638. zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
  639. }
  640. </pre></div>
  641. <p>
  642. To insert code into the <tt>PHP_MSHUTDOWN_FUNCTION</tt>, one can use
  643. either <tt>%shutdown</tt> or <tt>%mshutdown</tt>.
  644. </p>
  645. <div class="code"><pre>
  646. %module example;
  647. %mshutdown {
  648. zend_printf("Inserted into PHP_MSHUTDOWN_FUNCTION\n");
  649. }
  650. </pre></div>
  651. <p>
  652. The <tt>%rinit</tt> and <tt>%rshutdown</tt> statements are very similar but insert code
  653. into the request init (PHP_RINIT_FUNCTION) and request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively.
  654. </p>
  655. <H2><a name="Php_nn3"></a>32.3 Cross language polymorphism</H2>
  656. <p>
  657. Proxy classes provide a more natural, object-oriented way to access
  658. extension classes. As described above, each proxy instance has an
  659. associated C++ instance, and method calls to the proxy are passed to the
  660. C++ instance transparently via C wrapper functions.
  661. </p>
  662. <p>
  663. This arrangement is asymmetric in the sense that no corresponding
  664. mechanism exists to pass method calls down the inheritance chain from
  665. C++ to PHP. In particular, if a C++ class has been extended in PHP
  666. (by extending the proxy class), these extensions will not be visible
  667. from C++ code. Virtual method calls from C++ are thus not able access
  668. the lowest implementation in the inheritance chain.
  669. </p>
  670. <p>
  671. Changes have been made to SWIG 1.3.18 to address this problem and make
  672. the relationship between C++ classes and proxy classes more symmetric.
  673. To achieve this goal, new classes called directors are introduced at the
  674. bottom of the C++ inheritance chain. Support for generating PHP classes
  675. has been added in SWIG 1.3.40. The job of the directors is to route
  676. method calls correctly, either to C++ implementations higher in the
  677. inheritance chain or to PHP implementations lower in the inheritance
  678. chain. The upshot is that C++ classes can be extended in PHP and from
  679. C++ these extensions look exactly like native C++ classes. Neither C++
  680. code nor PHP code needs to know where a particular method is
  681. implemented: the combination of proxy classes, director classes, and C
  682. wrapper functions takes care of all the cross-language method routing
  683. transparently.
  684. </p>
  685. <H3><a name="Php_nn3_1"></a>32.3.1 Enabling directors</H3>
  686. <p>
  687. The director feature is disabled by default. To use directors you
  688. must make two changes to the interface file. First, add the "directors"
  689. option to the %module directive, like this:
  690. </p>
  691. <div class="code">
  692. <pre>
  693. %module(directors="1") modulename
  694. </pre>
  695. </div>
  696. <p>
  697. Without this option no director code will be generated. Second, you
  698. must use the %feature("director") directive to tell SWIG which classes
  699. and methods should get directors. The %feature directive can be applied
  700. globally, to specific classes, and to specific methods, like this:
  701. </p>
  702. <div class="code">
  703. <pre>
  704. // generate directors for all classes that have virtual methods
  705. %feature("director");
  706. // generate directors for all virtual methods in class Foo
  707. %feature("director") Foo;
  708. // generate a director for just Foo::bar()
  709. %feature("director") Foo::bar;
  710. </pre>
  711. </div>
  712. <p>
  713. You can use the %feature("nodirector") directive to turn off
  714. directors for specific classes or methods. So for example,
  715. </p>
  716. <div class="code">
  717. <pre>
  718. %feature("director") Foo;
  719. %feature("nodirector") Foo::bar;
  720. </pre>
  721. </div>
  722. <p>
  723. will generate directors for all virtual methods of class Foo except
  724. bar().
  725. </p>
  726. <p>
  727. Directors can also be generated implicitly through inheritance.
  728. In the following, class Bar will get a director class that handles
  729. the methods one() and two() (but not three()):
  730. </p>
  731. <div class="code">
  732. <pre>
  733. %feature("director") Foo;
  734. class Foo {
  735. public:
  736. Foo(int foo);
  737. virtual void one();
  738. virtual void two();
  739. };
  740. class Bar: public Foo {
  741. public:
  742. virtual void three();
  743. };
  744. </pre>
  745. </div>
  746. <p>
  747. then at the PHP side you can define
  748. </p>
  749. <div class="targetlang">
  750. <pre>
  751. require("mymodule.php");
  752. class MyFoo extends Foo {
  753. function one() {
  754. print "one from php\n";
  755. }
  756. }
  757. </pre>
  758. </div>
  759. <H3><a name="Php_nn3_2"></a>32.3.2 Director classes</H3>
  760. <p>
  761. For each class that has directors enabled, SWIG generates a new class
  762. that derives from both the class in question and a special
  763. <tt>Swig::Director</tt> class. These new classes, referred to as director
  764. classes, can be loosely thought of as the C++ equivalent of the PHP
  765. proxy classes. The director classes store a pointer to their underlying
  766. PHP object. Indeed, this is quite similar to the "_cPtr" and "thisown"
  767. members of the PHP proxy classes.
  768. </p>
  769. <p>
  770. For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the
  771. original C++ class as the director's base class. By default, a director
  772. class extends all virtual methods in the inheritance chain of its base
  773. class (see the preceding section for how to modify this behavior).
  774. Thus all virtual method calls, whether they originate in C++ or in
  775. PHP via proxy classes, eventually end up in at the implementation in the
  776. director class. The job of the director methods is to route these method
  777. calls to the appropriate place in the inheritance chain. By "appropriate
  778. place" we mean the method that would have been called if the C++ base
  779. class and its extensions in PHP were seamlessly integrated. That
  780. seamless integration is exactly what the director classes provide,
  781. transparently skipping over all the messy extension API glue that binds
  782. the two languages together.
  783. </p>
  784. <p>
  785. In reality, the "appropriate place" is one of only two possibilities:
  786. C++ or PHP. Once this decision is made, the rest is fairly easy. If the
  787. correct implementation is in C++, then the lowest implementation of the
  788. method in the C++ inheritance chain is called explicitly. If the correct
  789. implementation is in PHP, the Zend API is used to call the method of the
  790. underlying PHP object (after which the usual virtual method resolution
  791. in PHP automatically finds the right implementation).
  792. </p>
  793. <p>
  794. Now how does the director decide which language should handle the method call?
  795. The basic rule is to handle the method in PHP, unless there's a good
  796. reason not to. The reason for this is simple: PHP has the most
  797. "extended" implementation of the method. This assertion is guaranteed,
  798. since at a minimum the PHP proxy class implements the method. If the
  799. method in question has been extended by a class derived from the proxy
  800. class, that extended implementation will execute exactly as it should.
  801. If not, the proxy class will route the method call into a C wrapper
  802. function, expecting that the method will be resolved in C++. The wrapper
  803. will call the virtual method of the C++ instance, and since the director
  804. extends this the call will end up right back in the director method. Now
  805. comes the "good reason not to" part. If the director method were to blindly
  806. call the PHP method again, it would get stuck in an infinite loop. We avoid this
  807. situation by adding special code to the C wrapper function that tells
  808. the director method to not do this. The C wrapper function compares the
  809. called and the declaring class name of the given method. If these are
  810. not the same, then the C wrapper function tells the director to resolve
  811. the method by calling up the C++ inheritance chain, preventing an
  812. infinite loop.
  813. </p>
  814. <p>
  815. One more point needs to be made about the relationship between director
  816. classes and proxy classes. When a proxy class instance is created in
  817. PHP, SWIG creates an instance of the original C++ class and assigns it
  818. to <tt>-&gt;_cPtr</tt>. This is exactly what happens without directors
  819. and is true even if directors are enabled for the particular class in
  820. question. When a class <i>derived</i> from a proxy class is created,
  821. however, SWIG then creates an instance of the corresponding C++ director
  822. class. The reason for this difference is that user-defined subclasses
  823. may override or extend methods of the original class, so the director
  824. class is needed to route calls to these methods correctly. For
  825. unmodified proxy classes, all methods are ultimately implemented in C++
  826. so there is no need for the extra overhead involved with routing the
  827. calls through PHP.
  828. </p>
  829. <H3><a name="Php_nn3_3"></a>32.3.3 Ownership and object destruction</H3>
  830. <p>
  831. Memory management issues are slightly more complicated with directors
  832. than for proxy classes alone. PHP instances hold a pointer to the
  833. associated C++ director object, and the director in turn holds a pointer
  834. back to the PHP object. By default, proxy classes own their C++ director
  835. object and take care of deleting it when they are garbage collected.
  836. </p>
  837. <p>
  838. This relationship can be reversed by calling the special
  839. <tt>-&gt;thisown</tt> property of the proxy class. After setting this
  840. property to <tt>0</tt>, the director class no longer destroys the PHP
  841. object. Assuming no outstanding references to the PHP object remain,
  842. the PHP object will be destroyed at the same time. This is a good thing,
  843. since directors and proxies refer to each other and so must be created
  844. and destroyed together. Destroying one without destroying the other will
  845. likely cause your program to segfault.
  846. </p>
  847. <p>
  848. Here is an example:
  849. </p>
  850. <div class="code">
  851. <pre>
  852. class Foo {
  853. public:
  854. ...
  855. };
  856. class FooContainer {
  857. public:
  858. void addFoo(Foo *);
  859. ...
  860. };
  861. </pre>
  862. </div>
  863. <br>
  864. <div class="targetlang">
  865. <pre>
  866. $c = new FooContainer();
  867. $a = new Foo();
  868. $a-&gt;thisown = 0;
  869. $c-&gt;addFoo($a);
  870. </pre>
  871. </div>
  872. <p>
  873. In this example, we are assuming that FooContainer will take care of
  874. deleting all the Foo pointers it contains at some point.
  875. </p>
  876. <H3><a name="Php_nn3_4"></a>32.3.4 Exception unrolling</H3>
  877. <p>
  878. With directors routing method calls to PHP, and proxies routing them
  879. to C++, the handling of exceptions is an important concern. By default, the
  880. directors ignore exceptions that occur during method calls that are
  881. resolved in PHP. To handle such exceptions correctly, it is necessary
  882. to temporarily translate them into C++ exceptions. This can be done with
  883. the %feature("director:except") directive. The following code should
  884. suffice in most cases:
  885. </p>
  886. <div class="code">
  887. <pre>
  888. %feature("director:except") {
  889. if ($error == FAILURE) {
  890. throw Swig::DirectorMethodException();
  891. }
  892. }
  893. </pre>
  894. </div>
  895. <p>
  896. This code will check the PHP error state after each method call from a
  897. director into PHP, and throw a C++ exception if an error occurred. This
  898. exception can be caught in C++ to implement an error handler.
  899. Currently no information about the PHP error is stored in the
  900. Swig::DirectorMethodException object, but this will likely change in the
  901. future.
  902. </p>
  903. <p>
  904. It may be the case that a method call originates in PHP, travels up to
  905. C++ through a proxy class, and then back into PHP via a director method.
  906. If an exception occurs in PHP at this point, it would be nice for that
  907. exception to find its way back to the original caller. This can be done
  908. by combining a normal %exception directive with the
  909. <tt>director:except</tt> handler shown above. Here is an example of a
  910. suitable exception handler:
  911. </p>
  912. <div class="code">
  913. <pre>
  914. %exception {
  915. try { $action }
  916. catch (Swig::DirectorException &amp;e) { SWIG_fail; }
  917. }
  918. </pre>
  919. </div>
  920. <p>
  921. The class Swig::DirectorException used in this example is actually a
  922. base class of Swig::DirectorMethodException, so it will trap this
  923. exception. Because the PHP error state is still set when
  924. Swig::DirectorMethodException is thrown, PHP will register the exception
  925. as soon as the C wrapper function returns.
  926. </p>
  927. <H3><a name="Php_nn3_5"></a>32.3.5 Overhead and code bloat</H3>
  928. <p>
  929. Enabling directors for a class will generate a new director method for
  930. every virtual method in the class' inheritance chain. This alone can
  931. generate a lot of code bloat for large hierarchies. Method arguments
  932. that require complex conversions to and from target language types can
  933. result in large director methods. For this reason it is recommended that
  934. you selectively enable directors only for specific classes that are
  935. likely to be extended in PHP and used in C++.
  936. </p>
  937. <p>
  938. Compared to classes that do not use directors, the call routing in the
  939. director methods does add some overhead. In particular, at least one
  940. dynamic cast and one extra function call occurs per method call from
  941. PHP. Relative to the speed of PHP execution this is probably completely
  942. negligible. For worst case routing, a method call that ultimately
  943. resolves in C++ may take one extra detour through PHP in order to ensure
  944. that the method does not have an extended PHP implementation. This could
  945. result in a noticeable overhead in some cases.
  946. </p>
  947. <p>
  948. Although directors make it natural to mix native C++ objects with PHP
  949. objects (as director objects) via a common base class pointer, one
  950. should be aware of the obvious fact that method calls to PHP objects
  951. will be much slower than calls to C++ objects. This situation can be
  952. optimized by selectively enabling director methods (using the %feature
  953. directive) for only those methods that are likely to be extended in PHP.
  954. </p>
  955. <H3><a name="Php_nn3_6"></a>32.3.6 Typemaps</H3>
  956. <p>
  957. Typemaps for input and output of most of the basic types from director
  958. classes have been written. These are roughly the reverse of the usual
  959. input and output typemaps used by the wrapper code. The typemap
  960. operation names are 'directorin', 'directorout', and 'directorargout'.
  961. The director code does not currently use any of the other kinds of
  962. typemaps. It is not clear at this point which kinds are appropriate and
  963. need to be supported.
  964. </p>
  965. <H3><a name="Php_nn3_7"></a>32.3.7 Miscellaneous</H3>
  966. <p> Director typemaps for STL classes are mostly in place, and hence you
  967. should be able to use std::string, etc., as you would any other type.
  968. </p>
  969. </body>
  970. </html>