PageRenderTime 48ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/Examples/java/template/index.html

#
HTML | 102 lines | 78 code | 24 blank | 0 comment | 0 complexity | fa83fbb1b118aac9e81ab2b0ad7619f4 MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  1. <html>
  2. <head>
  3. <title>SWIG:Examples:java:template</title>
  4. </head>
  5. <body bgcolor="#ffffff">
  6. <tt>SWIG/Examples/java/template/</tt>
  7. <hr>
  8. <H2>C++ template support</H2>
  9. <p>
  10. This example illustrates how C++ templates can be used from Java using SWIG.
  11. <h2>The C++ Code</h2>
  12. Lets take a templated function and a templated class as follows:
  13. <blockquote>
  14. <pre>
  15. /* File : example.h */
  16. // Some template definitions
  17. template<class T> T max(T a, T b) { return a&gt;b ? a : b; }
  18. template<class T> class vector {
  19. T *v;
  20. int sz;
  21. public:
  22. vector(int _sz) {
  23. v = new T[_sz];
  24. sz = _sz;
  25. }
  26. T &amp;get(int index) {
  27. return v[index];
  28. }
  29. void set(int index, T &amp;val) {
  30. v[index] = val;
  31. }
  32. #ifdef SWIG
  33. %addmethods {
  34. T getitem(int index) {
  35. return self-&gt;get(index);
  36. }
  37. void setitem(int index, T val) {
  38. self-&gt;set(index,val);
  39. }
  40. }
  41. #endif
  42. };
  43. </pre>
  44. </blockquote>
  45. The %addmethods is used for a neater interface from Java as the functions <tt>get</tt> and <tt>set</tt> use C++ references to primitive types. These are tricky to use from Java as they end up as a pointer in Java (Java long).
  46. <h2>The SWIG interface</h2>
  47. A simple SWIG interface for this can be built by simply grabbing the header file
  48. like this:
  49. <blockquote>
  50. <pre>
  51. /* File : example.i */
  52. %module example
  53. %{
  54. #include "example.h"
  55. %}
  56. /* Let's just grab the original header file here */
  57. %include "example.h"
  58. /* Now instantiate some specific template declarations */
  59. %template(maxint) max<int>;
  60. %template(maxdouble) max<double>;
  61. %template(vecint) vector<int>;
  62. %template(vecdouble) vector<double>;
  63. </pre>
  64. </blockquote>
  65. Note that SWIG parses the templated function <tt>max</tt> and templated class <tt>vector</tt> and so knows about them. However to generate code for use from Java, SWIG has to be told which class/type to use as the template parameter. The SWIG directive %template is used for this.
  66. <h2>A sample Java program</h2>
  67. Click <a href="runme.java">here</a> to see a Java program that calls the C++ functions from Java.
  68. <h2>Notes</h2>
  69. Use templated classes just like you would any other SWIG generated Java class. Use the classnames specified by the %template directive.
  70. <blockquote>
  71. <pre>
  72. vecdouble dv = new vecdouble(1000);
  73. dv.setitem(i, 12.34));
  74. </pre>
  75. </blockquote>
  76. <hr>
  77. </body>
  78. </html>