PageRenderTime 49ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/rel-1.3.35/Examples/python/varargs/example.i

#
Swig | 65 lines | 34 code | 13 blank | 18 comment | 0 complexity | 50884c55f96e066f7d5b8d62f5167625 MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  1. /* File : example.i */
  2. %module example
  3. %{
  4. #include <stdarg.h>
  5. %}
  6. /* This example illustrates SWIG's handling of varargs functions.
  7. By default, variable length arguments are simply ignored. This
  8. is generally appropriate for wrapping I/O functions like printf.
  9. You can simply format a string in the scripting language, and
  10. pass it directly */
  11. int printf(const char *fmt, ...);
  12. /* Since passing a format string might be dangerous. Here is a slightly
  13. different way of wrapping a printf style function */
  14. #if 1
  15. /* Replace ... with char *. */
  16. %varargs(char *) fprintf;
  17. /* Ignore the format string, but set it to %s */
  18. %typemap(in,numinputs=0) const char *fmt {
  19. $1 = "%s";
  20. }
  21. #else
  22. /* An alternative approach using typemaps */
  23. %typemap(in) (const char *fmt, ...) {
  24. $1 = "%s";
  25. $2 = (void *) PyString_AsString($input);
  26. }
  27. #endif
  28. /* Typemap just to make the example work */
  29. %typemap(in) FILE * "$1 = PyFile_AsFile($input);";
  30. int fprintf(FILE *, const char *fmt, ...);
  31. /* Here is somewhat different example. A variable length argument
  32. function that takes a NULL-terminated list of arguments. We
  33. can use a slightly different form of %varargs that specifies
  34. a default value and a maximum number of arguments.
  35. */
  36. /* Maximum of 20 arguments with default value NULL */
  37. %varargs(20, char *x = NULL) printv;
  38. %inline %{
  39. void printv(char *s, ...) {
  40. va_list ap;
  41. char *x;
  42. fputs(s,stdout);
  43. fputc(' ',stdout);
  44. va_start(ap, s);
  45. while ((x = va_arg(ap, char *))) {
  46. fputs(x,stdout);
  47. fputc(' ',stdout);
  48. }
  49. va_end(ap);
  50. fputc('\n',stdout);
  51. }
  52. %}