PageRenderTime 44ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/ttn-post-libtool-1-4-3-upgrade/SWIG/Examples/python/funcptr/index.html

#
HTML | 92 lines | 67 code | 25 blank | 0 comment | 0 complexity | 44ae50abf78e94e08ebc5d4465b4c911 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:python:funcptr</title>
  4. </head>
  5. <body bgcolor="#ffffff">
  6. <tt>SWIG/Examples/python/funcptr/</tt>
  7. <hr>
  8. <H2>Pointers to Functions</H2>
  9. <tt>$Header$</tt><br>
  10. <p>
  11. Okay, just what in the heck does SWIG do with a declaration like this?
  12. <blockquote>
  13. <pre>
  14. int do_op(int a, int b, int (*op)(int, int));
  15. </pre>
  16. </blockquote>
  17. Well, it creates a wrapper as usual. Of course, that does raise some
  18. questions about the third argument (the pointer to a function).
  19. <p>
  20. In this case, SWIG will wrap the function pointer as it does for all other
  21. pointers. However, in order to actually call this function from a script,
  22. you will need to pass some kind of C function pointer object. In C,
  23. this is easy, you just supply a function name as an argument like this:
  24. <blockquote>
  25. <pre>
  26. /* Some callback function */
  27. int add(int a, int b) {
  28. return a+b;
  29. }
  30. ...
  31. int r = do_op(x,y,add);
  32. </pre>
  33. </blockquote>
  34. To make this work with SWIG, you will need to do a little extra work. Specifically,
  35. you need to create some function pointer objects using the %constant directive like this:
  36. <blockquote>
  37. <pre>
  38. %constant(int (*)(int,int)) ADD = add;
  39. </pre>
  40. </blockquote>
  41. Now, in a script, you would do this:
  42. <blockquote>
  43. <pre>
  44. r = do_op(x,y, ADD)
  45. </pre>
  46. </blockquote>
  47. <h2>An Example</h2>
  48. Here are some files that illustrate this with a simple example:
  49. <ul>
  50. <li><a href="example.c">example.c</a>
  51. <li><a href="example.h">example.h</a>
  52. <li><a href="example.i">example.i</a> (SWIG interface)
  53. <li><a href="example.py">example.py</a> (Sample script)
  54. </ul>
  55. <h2>Notes</h2>
  56. <ul>
  57. <li>The value of a function pointer must correspond to a function written in C or C++.
  58. It is not possible to pass an arbitrary Python function object in as a substitute for a C
  59. function pointer.
  60. <p>
  61. <li>A python function can be used as a C/C++ callback if you write some
  62. clever typemaps and are very careful about how you create your extension.
  63. This is an advanced topic not covered here.
  64. </ul>
  65. <hr>
  66. </body>
  67. </html>