PageRenderTime 42ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/Examples/ruby/funcptr/index.html

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