/tags/rel-2.0.0/Doc/Manual/Varargs.html

# · HTML · 941 lines · 802 code · 137 blank · 2 comment · 0 complexity · 04a5e8d9b73602c7b0c87f68c8448303 MD5 · raw file

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <title>Variable Length Arguments</title>
  5. <link rel="stylesheet" type="text/css" href="style.css">
  6. </head>
  7. <body bgcolor="#ffffff">
  8. <H1><a name="Varargs"></a>13 Variable Length Arguments</H1>
  9. <!-- INDEX -->
  10. <div class="sectiontoc">
  11. <ul>
  12. <li><a href="#Varargs_nn2">Introduction</a>
  13. <li><a href="#Varargs_nn3">The Problem</a>
  14. <li><a href="#Varargs_nn4">Default varargs support</a>
  15. <li><a href="#Varargs_nn5">Argument replacement using %varargs</a>
  16. <li><a href="#Varargs_nn6">Varargs and typemaps</a>
  17. <li><a href="#Varargs_nn7">Varargs wrapping with libffi</a>
  18. <li><a href="#Varargs_nn8">Wrapping of va_list</a>
  19. <li><a href="#Varargs_nn9">C++ Issues</a>
  20. <li><a href="#Varargs_nn10">Discussion</a>
  21. </ul>
  22. </div>
  23. <!-- INDEX -->
  24. <p>
  25. <b>(a.k.a, "The horror. The horror.")</b>
  26. </p>
  27. <p>
  28. This chapter describes the problem of wrapping functions that take a
  29. variable number of arguments. For instance, generating wrappers for
  30. the C <tt>printf()</tt> family of functions.
  31. </p>
  32. <p>
  33. This topic is sufficiently advanced to merit its own chapter. In
  34. fact, support for varargs is an often requested feature that was first
  35. added in SWIG-1.3.12. Most other wrapper generation tools have
  36. wisely chosen to avoid this issue.
  37. </p>
  38. <H2><a name="Varargs_nn2"></a>13.1 Introduction</H2>
  39. <p>
  40. Some C and C++ programs may include functions that accept a variable
  41. number of arguments. For example, most programmers are
  42. familiar with functions from the C library such as the following:
  43. </p>
  44. <div class="code">
  45. <pre>
  46. int printf(const char *fmt, ...)
  47. int fprintf(FILE *, const char *fmt, ...);
  48. int sprintf(char *s, const char *fmt, ...);
  49. </pre>
  50. </div>
  51. <p>
  52. Although there is probably little practical purpose in wrapping these
  53. specific C library functions in a scripting language (what would be the
  54. point?), a library may include its own set of special functions based
  55. on a similar API. For example:
  56. </p>
  57. <div class="code">
  58. <pre>
  59. int traceprintf(const char *fmt, ...);
  60. </pre>
  61. </div>
  62. <p>
  63. In this case, you may want to have some kind of access from the target language.
  64. </p>
  65. <p>
  66. Before describing the SWIG implementation, it is important to discuss
  67. the common uses of varargs that you are likely to encounter in real
  68. programs. Obviously, there are the <tt>printf()</tt> style output
  69. functions as shown. Closely related to this would be
  70. <tt>scanf()</tt> style input functions that accept a format string and a
  71. list of pointers into which return values are placed. However, variable
  72. length arguments are also sometimes used to write functions that accept a
  73. NULL-terminated list of pointers. A good example of this would
  74. be a function like this:
  75. </p>
  76. <div class="code">
  77. <pre>
  78. int execlp(const char *path, const char *arg1, ...);
  79. ...
  80. /* Example */
  81. execlp("ls","ls","-l",NULL);
  82. </pre>
  83. </div>
  84. <p>
  85. In addition, varargs is sometimes used to fake default arguments in older
  86. C libraries. For instance, the low level <tt>open()</tt> system call
  87. is often declared as a varargs function so that it will accept two
  88. or three arguments:
  89. </p>
  90. <div class="code">
  91. <pre>
  92. int open(const char *path, int oflag, ...);
  93. ...
  94. /* Examples */
  95. f = open("foo", O_RDONLY);
  96. g = open("bar", O_WRONLY | O_CREAT, 0644);
  97. </pre>
  98. </div>
  99. <p>
  100. Finally, to implement a varargs function, recall that you have to use
  101. the C library functions defined in <tt>&lt;stdarg.h&gt;</tt>. For
  102. example:
  103. </p>
  104. <div class="code">
  105. <pre>
  106. List make_list(const char *s, ...) {
  107. va_list ap;
  108. List x;
  109. ...
  110. va_start(ap, s);
  111. while (s) {
  112. x.append(s);
  113. s = va_arg(ap, const char *);
  114. }
  115. va_end(ap);
  116. return x;
  117. }
  118. </pre>
  119. </div>
  120. <H2><a name="Varargs_nn3"></a>13.2 The Problem</H2>
  121. <p>
  122. Generating wrappers for a variable length argument function presents a
  123. number of special challenges. Although C provides support for
  124. implementing functions that receive variable length arguments, there
  125. are no functions that can go in the other direction. Specifically,
  126. you can't write a function that dynamically creates a list of
  127. arguments and which invokes a varargs function on your behalf.
  128. </p>
  129. <p>
  130. Although it is possible to write functions that accept the special
  131. type <tt>va_list</tt>, this is something entirely different. You
  132. can't take a <tt>va_list</tt> structure and pass it in place of the
  133. variable length arguments to another varargs function. It just
  134. doesn't work.
  135. </p>
  136. <p>
  137. The reason this doesn't work has to do with the way that function
  138. calls get compiled. For example, suppose that your program has a function call like this:
  139. </p>
  140. <div class="code">
  141. <pre>
  142. printf("Hello %s. Your number is %d\n", name, num);
  143. </pre>
  144. </div>
  145. <p>
  146. When the compiler looks at this, it knows that you are calling
  147. <tt>printf()</tt> with exactly three arguments. Furthermore, it knows
  148. that the number of arguments as well are their types and sizes is
  149. <em>never</em> going to change during program execution. Therefore,
  150. this gets turned to machine code that sets up a three-argument stack
  151. frame followed by a call to <tt>printf()</tt>.
  152. </p>
  153. <p>
  154. In contrast, suppose you attempted to make some kind of wrapper around
  155. <tt>printf()</tt> using code like this:
  156. </p>
  157. <div class="code">
  158. <pre>
  159. int wrap_printf(const char *fmt, ...) {
  160. va_list ap;
  161. va_start(ap,fmt);
  162. ...
  163. printf(fmt,ap);
  164. ...
  165. va_end(ap);
  166. };
  167. </pre>
  168. </div>
  169. <p>
  170. Although this code might compile, it won't do what you expect. This is
  171. because the call to <tt>printf()</tt> is compiled as a procedure call
  172. involving only two arguments. However, clearly a two-argument
  173. configuration of the call stack is completely wrong if your intent is
  174. to pass an arbitrary number of arguments to the real
  175. <tt>printf()</tt>. Needless to say, it won't work.
  176. </p>
  177. <p>
  178. Unfortunately, the situation just described is exactly the problem
  179. faced by wrapper generation tools. In general, the number of passed
  180. arguments will not be known until run-time. To make matters even
  181. worse, you won't know the types and sizes of arguments until run-time
  182. as well. Needless to say, there is no obvious way to make the C
  183. compiler generate code for a function call involving an unknown number
  184. of arguments of unknown types.
  185. </p>
  186. <p>
  187. In theory, it <em>is</em> possible to write a wrapper that does the right thing.
  188. However, this involves knowing the underlying ABI for the target platform and language
  189. as well as writing special purpose code that manually constructed the call stack before
  190. making a procedure call. Unfortunately, both of these tasks require the use of inline
  191. assembly code. Clearly, that's the kind of solution you would much rather avoid.
  192. </p>
  193. <p>
  194. With this nastiness in mind, SWIG provides a number of solutions to the varargs
  195. wrapping problem. Most of these solutions are compromises that provide limited
  196. varargs support without having to resort to assembly language. However, SWIG
  197. can also support real varargs wrapping (with stack-frame manipulation) if you
  198. are willing to get hands dirty. Keep reading.
  199. </p>
  200. <H2><a name="Varargs_nn4"></a>13.3 Default varargs support</H2>
  201. <p>
  202. When variable length arguments appear in an interface, the default
  203. behavior is to drop the variable argument list entirely, replacing
  204. them with a single NULL pointer. For example, if you had this
  205. function,
  206. </p>
  207. <div class="code">
  208. <pre>
  209. void traceprintf(const char *fmt, ...);
  210. </pre>
  211. </div>
  212. <p>
  213. it would be wrapped as if it had been declared as follows:
  214. </p>
  215. <div class="code">
  216. <pre>
  217. void traceprintf(const char *fmt);
  218. </pre>
  219. </div>
  220. <p>
  221. When the function is called inside the wrappers, it is called as follows:
  222. </p>
  223. <div class="code">
  224. <pre>
  225. traceprintf(arg1, NULL);
  226. </pre>
  227. </div>
  228. <p>
  229. Arguably, this approach seems to defeat the whole point of variable length arguments. However,
  230. this actually provides enough support for many simple kinds of varargs functions to still be useful, however it does come with a caveat.
  231. For instance, you could make function calls like this (in Python):
  232. </p>
  233. <div class="targetlang">
  234. <pre>
  235. &gt;&gt;&gt; traceprintf("Hello World")
  236. &gt;&gt;&gt; traceprintf("Hello %s. Your number is %d\n" % (name, num))
  237. &gt;&gt;&gt; traceprintf("Your result is 90%%.")
  238. </pre>
  239. </div>
  240. <p>
  241. Notice how string formatting is being done in Python instead of C.
  242. The caveat is the strings passed must be safe to use in C though.
  243. For example if name was to contain a "%" it should be double escaped in order to avoid unpredictable
  244. behaviour:
  245. </p>
  246. <div class="targetlang">
  247. <pre>
  248. &gt;&gt;&gt; traceprintf("Your result is 90%.\n") # unpredictable behaviour
  249. &gt;&gt;&gt; traceprintf("Your result is 90%%.\n") # good
  250. </pre>
  251. </div>
  252. <p>
  253. Read on for further solutions.
  254. </p>
  255. <H2><a name="Varargs_nn5"></a>13.4 Argument replacement using %varargs</H2>
  256. <p>
  257. Instead of dropping the variable length arguments, an alternative approach is to replace
  258. <tt>(...)</tt> with a set of suitable arguments. SWIG provides a special <tt>%varargs</tt> directive
  259. that can be used to do this. For example,
  260. </p>
  261. <div class="code">
  262. <pre>
  263. %varargs(int mode = 0) open;
  264. ...
  265. int open(const char *path, int oflags, ...);
  266. </pre>
  267. </div>
  268. <p>
  269. is equivalent to this:
  270. </p>
  271. <div class="code">
  272. <pre>
  273. int open(const char *path, int oflags, int mode = 0);
  274. </pre>
  275. </div>
  276. <p>
  277. In this case, <tt>%varargs</tt> is simply providing more specific information about the
  278. extra arguments that might be passed to a function.
  279. If the parameters to a varargs function are of uniform type, <tt>%varargs</tt> can also
  280. accept a numerical argument count as follows:
  281. </p>
  282. <div class="code">
  283. <pre>
  284. %varargs(10,char *arg = NULL) execlp;
  285. ...
  286. int execlp(const char *path, const char *arg1, ...);
  287. </pre>
  288. </div>
  289. <p>
  290. This would wrap <tt>execlp()</tt> as a function that accepted up to 10 optional arguments.
  291. Depending on the application, this may be more than enough for practical purposes.
  292. </p>
  293. <p>
  294. Argument replacement is most appropriate in cases where the types of
  295. the extra arguments is uniform and the maximum number of arguments is
  296. known. When replicated argument replacement is used, at least one extra
  297. argument is added to the end of the arguments when making the function call.
  298. This argument serves as a sentinel to make sure the list is properly terminated.
  299. It has the same value as that supplied to the <tt>%varargs</tt> directive.
  300. </p>
  301. <p>
  302. Argument replacement is not as useful when working with functions that accept
  303. mixed argument types such as <tt>printf()</tt>. Providing general purpose
  304. wrappers to such functions presents special problems (covered shortly).
  305. </p>
  306. <H2><a name="Varargs_nn6"></a>13.5 Varargs and typemaps</H2>
  307. <p>
  308. Variable length arguments may be used in typemap specifications. For example:
  309. </p>
  310. <div class="code">
  311. <pre>
  312. %typemap(in) (...) {
  313. // Get variable length arguments (somehow)
  314. ...
  315. }
  316. %typemap(in) (const char *fmt, ...) {
  317. // Multi-argument typemap
  318. }
  319. </pre>
  320. </div>
  321. <p>
  322. However, this immediately raises the question of what "type" is actually used
  323. to represent <tt>(...)</tt>. For lack of a better alternative, the type of
  324. <tt>(...)</tt> is set to <tt>void *</tt>. Since there is no
  325. way to dynamically pass arguments to a varargs function (as previously described),
  326. the <tt>void *</tt> argument value is intended to serve as a place holder
  327. for storing some kind of information about the extra arguments (if any). In addition, the
  328. default behavior of SWIG is to pass the <tt>void *</tt> value as an argument to
  329. the function. Therefore, you could use the pointer to hold a valid argument value if you wanted.
  330. </p>
  331. <p>
  332. To illustrate, here is a safer version of wrapping <tt>printf()</tt> in Python:
  333. </p>
  334. <div class="code">
  335. <pre>
  336. %typemap(in) (const char *fmt, ...) {
  337. $1 = "%s"; /* Fix format string to %s */
  338. $2 = (void *) PyString_AsString($input); /* Get string argument */
  339. };
  340. ...
  341. int printf(const char *fmt, ...);
  342. </pre>
  343. </div>
  344. <p>
  345. In this example, the format string is implicitly set to <tt>"%s"</tt>.
  346. This prevents a program from passing a bogus format string to the
  347. extension. Then, the passed input object is decoded and placed in the
  348. <tt>void *</tt> argument defined for the <tt>(...)</tt> argument. When the
  349. actual function call is made, the underlying wrapper code will look roughly
  350. like this:
  351. </p>
  352. <div class="code">
  353. <pre>
  354. wrap_printf() {
  355. char *arg1;
  356. void *arg2;
  357. int result;
  358. arg1 = "%s";
  359. arg2 = (void *) PyString_AsString(arg2obj);
  360. ...
  361. result = printf(arg1,arg2);
  362. ...
  363. }
  364. </pre>
  365. </div>
  366. <p>
  367. Notice how both arguments are passed to the function and it does what you
  368. would expect.
  369. </p>
  370. <p>
  371. The next example illustrates a more advanced kind of varargs typemap.
  372. Disclaimer: this requires special support in the target language module and is not
  373. guaranteed to work with all SWIG modules at this time. It also starts to illustrate
  374. some of the more fundamental problems with supporting varargs in more generality.
  375. </p>
  376. <p>
  377. If a typemap is defined for any form of <tt>(...)</tt>, many SWIG
  378. modules will generate wrappers that accept a variable number of
  379. arguments as input and will make these arguments available in some
  380. form. The precise details of this depends on the language module
  381. being used (consult the appropriate chapter for more details).
  382. However, suppose that you wanted to create a Python wrapper for the
  383. <tt>execlp()</tt> function shown earlier. To do this using a typemap
  384. instead of using <tt>%varargs</tt>, you might first write a typemap
  385. like this:
  386. </p>
  387. <div class="code">
  388. <pre>
  389. %typemap(in) (...)(char *args[10]) {
  390. int i;
  391. int argc;
  392. for (i = 0; i &lt; 10; i++) args[i] = 0;
  393. argc = PyTuple_Size(varargs);
  394. if (argc &gt; 10) {
  395. PyErr_SetString(PyExc_ValueError,"Too many arguments");
  396. return NULL;
  397. }
  398. for (i = 0; i &lt; argc; i++) {
  399. PyObject *o = PyTuple_GetItem(varargs,i);
  400. if (!PyString_Check(o)) {
  401. PyErr_SetString(PyExc_ValueError,"Expected a string");
  402. return NULL;
  403. }
  404. args[i] = PyString_AsString(o);
  405. }
  406. $1 = (void *) args;
  407. }
  408. </pre>
  409. </div>
  410. <p>
  411. In this typemap, the special variable <tt>varargs</tt> is a tuple
  412. holding all of the extra arguments passed (this is specific to the
  413. Python module). The typemap then pulls this apart and sticks the
  414. values into the array of strings <tt>args</tt>. Then, the array is
  415. assigned to <tt>$1</tt> (recall that this is the <tt>void *</tt>
  416. variable corresponding to <tt>(...)</tt>). However, this assignment
  417. is only half of the picture----clearly this alone is not enough to
  418. make the function work. To patch everything up, you have to rewrite the
  419. underlying action code using the <tt>%feature</tt> directive like
  420. this:
  421. </p>
  422. <div class="code">
  423. <pre>
  424. %feature("action") execlp {
  425. char *args = (char **) arg3;
  426. result = execlp(arg1, arg2, args[0], args[1], args[2], args[3], args[4],
  427. args[5],args[6],args[7],args[8],args[9], NULL);
  428. }
  429. int execlp(const char *path, const char *arg, ...);
  430. </pre>
  431. </div>
  432. <p>
  433. This patches everything up and creates a function that more or less
  434. works. However, don't try explaining this to your coworkers unless
  435. you know for certain that they've had several cups of coffee. If you
  436. really want to elevate your guru status and increase your job
  437. security, continue to the next section.
  438. </p>
  439. <H2><a name="Varargs_nn7"></a>13.6 Varargs wrapping with libffi</H2>
  440. <p>
  441. All of the previous examples have relied on features of SWIG that are
  442. portable and which don't rely upon any low-level machine-level
  443. details. In many ways, they have all dodged the real issue of variable
  444. length arguments by recasting a varargs function into some weaker variation
  445. with a fixed number of arguments of known types. In many cases, this
  446. works perfectly fine. However, if you want more generality than this,
  447. you need to bring out some bigger guns.
  448. </p>
  449. <p>
  450. One way to do this is to use a special purpose library such as libffi
  451. (<a
  452. href="http://sources.redhat.com/libffi/">http://sources.redhat.com/libffi</a>).
  453. libffi is a library that allows you to dynamically construct
  454. call-stacks and invoke procedures in a relatively platform independent
  455. manner. Details about the library can be found in the libffi
  456. distribution and are not repeated here.
  457. </p>
  458. <p>
  459. To illustrate the use of libffi, suppose that you <em>really</em> wanted to create a
  460. wrapper for <tt>execlp()</tt> that accepted <em>any</em> number of
  461. arguments. To do this, you might make a few adjustments to the previous
  462. example. For example:
  463. </p>
  464. <div class="code">
  465. <pre>
  466. /* Take an arbitrary number of extra arguments and place into an array
  467. of strings */
  468. %typemap(in) (...) {
  469. char **argv;
  470. int argc;
  471. int i;
  472. argc = PyTuple_Size(varargs);
  473. argv = (char **) malloc(sizeof(char *)*(argc+1));
  474. for (i = 0; i &lt; argc; i++) {
  475. PyObject *o = PyTuple_GetItem(varargs,i);
  476. if (!PyString_Check(o)) {
  477. PyErr_SetString(PyExc_ValueError,"Expected a string");
  478. free(argv);
  479. return NULL;
  480. }
  481. argv[i] = PyString_AsString(o);
  482. }
  483. argv[i] = NULL;
  484. $1 = (void *) argv;
  485. }
  486. /* Rewrite the function call, using libffi */
  487. %feature("action") execlp {
  488. int i, vc;
  489. ffi_cif cif;
  490. ffi_type **types;
  491. void **values;
  492. char **args;
  493. vc = PyTuple_Size(varargs);
  494. types = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *));
  495. values = (void **) malloc((vc+3)*sizeof(void *));
  496. args = (char **) arg3;
  497. /* Set up path parameter */
  498. types[0] = &amp;ffi_type_pointer;
  499. values[0] = &amp;arg1;
  500. /* Set up first argument */
  501. types[1] = &amp;ffi_type_pointer;
  502. values[1] = &amp;arg2;
  503. /* Set up rest of parameters */
  504. for (i = 0; i &lt;= vc; i++) {
  505. types[2+i] = &amp;ffi_type_pointer;
  506. values[2+i] = &amp;args[i];
  507. }
  508. if (ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, vc+3,
  509. &amp;ffi_type_uint, types) == FFI_OK) {
  510. ffi_call(&amp;cif, (void (*)()) execlp, &amp;result, values);
  511. } else {
  512. PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
  513. free(types);
  514. free(values);
  515. free(arg3);
  516. return NULL;
  517. }
  518. free(types);
  519. free(values);
  520. free(arg3);
  521. }
  522. /* Declare the function. Whew! */
  523. int execlp(const char *path, const char *arg1, ...);
  524. </pre>
  525. </div>
  526. <p>
  527. Looking at this example, you may start to wonder if SWIG is making
  528. life any easier. Given the amount of code involved, you might also wonder
  529. why you didn't just write a hand-crafted wrapper! Either that or you're wondering
  530. "why in the hell am I trying to wrap this varargs function in the
  531. first place?!?" Obviously, those are questions you'll have to answer for yourself.
  532. </p>
  533. <p>
  534. As a more extreme example of libffi, here is some code that attempts to wrap <tt>printf()</tt>,
  535. </p>
  536. <div class="code">
  537. <pre>
  538. /* A wrapper for printf() using libffi */
  539. %{
  540. /* Structure for holding passed arguments after conversion */
  541. typedef struct {
  542. int type;
  543. union {
  544. int ivalue;
  545. double dvalue;
  546. void *pvalue;
  547. } val;
  548. } vtype;
  549. enum { VT_INT, VT_DOUBLE, VT_POINTER };
  550. %}
  551. %typemap(in) (const char *fmt, ...) {
  552. vtype *argv;
  553. int argc;
  554. int i;
  555. /* Format string */
  556. $1 = PyString_AsString($input);
  557. /* Variable length arguments */
  558. argc = PyTuple_Size(varargs);
  559. argv = (vtype *) malloc(argc*sizeof(vtype));
  560. for (i = 0; i &lt; argc; i++) {
  561. PyObject *o = PyTuple_GetItem(varargs,i);
  562. if (PyInt_Check(o)) {
  563. argv[i].type = VT_INT;
  564. argv[i].val.ivalue = PyInt_AsLong(o);
  565. } else if (PyFloat_Check(o)) {
  566. argv[i].type = VT_DOUBLE;
  567. argv[i].val.dvalue = PyFloat_AsDouble(o);
  568. } else if (PyString_Check(o)) {
  569. argv[i].type = VT_POINTER;
  570. argv[i].val.pvalue = (void *) PyString_AsString(o);
  571. } else {
  572. PyErr_SetString(PyExc_ValueError,"Unsupported argument type");
  573. free(argv);
  574. return NULL;
  575. }
  576. }
  577. $2 = (void *) argv;
  578. }
  579. /* Rewrite the function call using libffi */
  580. %feature("action") printf {
  581. int i, vc;
  582. ffi_cif cif;
  583. ffi_type **types;
  584. void **values;
  585. vtype *args;
  586. vc = PyTuple_Size(varargs);
  587. types = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *));
  588. values = (void **) malloc((vc+1)*sizeof(void *));
  589. args = (vtype *) arg2;
  590. /* Set up fmt parameter */
  591. types[0] = &amp;ffi_type_pointer;
  592. values[0] = &amp;arg1;
  593. /* Set up rest of parameters */
  594. for (i = 0; i &lt; vc; i++) {
  595. switch(args[i].type) {
  596. case VT_INT:
  597. types[1+i] = &amp;ffi_type_uint;
  598. values[1+i] = &amp;args[i].val.ivalue;
  599. break;
  600. case VT_DOUBLE:
  601. types[1+i] = &amp;ffi_type_double;
  602. values[1+i] = &amp;args[i].val.dvalue;
  603. break;
  604. case VT_POINTER:
  605. types[1+i] = &amp;ffi_type_pointer;
  606. values[1+i] = &amp;args[i].val.pvalue;
  607. break;
  608. default:
  609. abort(); /* Whoa! We're seriously hosed */
  610. break;
  611. }
  612. }
  613. if (ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, vc+1,
  614. &amp;ffi_type_uint, types) == FFI_OK) {
  615. ffi_call(&amp;cif, (void (*)()) printf, &amp;result, values);
  616. } else {
  617. PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
  618. free(types);
  619. free(values);
  620. free(args);
  621. return NULL;
  622. }
  623. free(types);
  624. free(values);
  625. free(args);
  626. }
  627. /* The function */
  628. int printf(const char *fmt, ...);
  629. </pre>
  630. </div>
  631. <p>
  632. Much to your amazement, it even seems to work if you try it:
  633. </p>
  634. <div class="targetlang">
  635. <pre>
  636. &gt;&gt;&gt; import example
  637. &gt;&gt;&gt; example.printf("Grade: %s %d/60 = %0.2f%%\n", "Dave", 47, 47.0*100/60)
  638. Grade: Dave 47/60 = 78.33%
  639. &gt;&gt;&gt;
  640. </pre>
  641. </div>
  642. <p>
  643. Of course, there are still some limitations to consider:
  644. </p>
  645. <div class="targetlang">
  646. <pre>
  647. &gt;&gt;&gt; example.printf("la de da de da %s", 42)
  648. Segmentation fault (core dumped)
  649. </pre>
  650. </div>
  651. <p>
  652. And, on this note, we leave further exploration of libffi to the reader as an exercise. Although Python has been used as an example,
  653. most of the techniques in this section can be extrapolated to other language modules with a bit of work. The only
  654. details you need to know is how the extra arguments are accessed in each target language. For example, in the Python
  655. module, we used the special <tt>varargs</tt> variable to get these arguments. Modules such as Tcl8 and Perl5 simply
  656. provide an argument number for the first extra argument. This can be used to index into an array of passed arguments to get
  657. values. Please consult the chapter on each language module for more details.
  658. </p>
  659. <H2><a name="Varargs_nn8"></a>13.7 Wrapping of va_list</H2>
  660. <p>
  661. Closely related to variable length argument wrapping, you may encounter functions that accept a parameter
  662. of type <tt>va_list</tt>. For example:
  663. </p>
  664. <div class="code">
  665. <pre>
  666. int vfprintf(FILE *f, const char *fmt, va_list ap);
  667. </pre>
  668. </div>
  669. <p>
  670. As far as we know, there is no obvious way to wrap these functions
  671. with SWIG. This is because there is no documented way to assemble the
  672. proper va_list structure (there are no C library functions to do it
  673. and the contents of va_list are opaque). Not only that, the contents
  674. of a <tt>va_list</tt> structure are closely tied to the underlying
  675. call-stack. It's not clear that exporting a <tt>va_list</tt> would
  676. have any use or that it would work at all.
  677. </p>
  678. <H2><a name="Varargs_nn9"></a>13.8 C++ Issues</H2>
  679. <p>
  680. Wrapping of C++ member functions that accept a variable number of
  681. arguments presents a number of challenges. By far, the easiest way to
  682. handle this is to use the <tt>%varargs</tt> directive. This is portable
  683. and it fully supports classes much like the <tt>%rename</tt> directive. For example:
  684. </p>
  685. <div class="code">
  686. <pre>
  687. %varargs (10, char * = NULL) Foo::bar;
  688. class Foo {
  689. public:
  690. virtual void bar(char *arg, ...); // gets varargs above
  691. };
  692. class Spam: public Foo {
  693. public:
  694. virtual void bar(char *arg, ...); // gets varargs above
  695. };
  696. </pre>
  697. </div>
  698. <p>
  699. <tt>%varargs</tt> also works with constructors, operators, and any
  700. other C++ programming construct that accepts variable arguments.
  701. </p>
  702. <p>
  703. Doing anything more advanced than this is likely to involve a serious
  704. world of pain. In order to use a library like libffi, you will need
  705. to know the underlying calling conventions and details of the C++ ABI. For
  706. instance, the details of how <tt>this</tt> is passed to member
  707. functions as well as any hidden arguments that might be used to pass
  708. additional information. These details are implementation specific and
  709. may differ between compilers and even different versions of the same
  710. compiler. Also, be aware that invoking a member function is further
  711. complicated if it is a virtual method. In this case,
  712. invocation might require a table lookup to obtain the proper function address
  713. (although you might be able to obtain an address by casting a bound
  714. pointer to a pointer to function as described in the C++ ARM section
  715. 18.3.4).
  716. </p>
  717. <p>
  718. If you do decide to change the underlying action code, be aware that SWIG
  719. always places the <tt>this</tt> pointer in <tt>arg1</tt>. Other arguments
  720. are placed in <tt>arg2</tt>, <tt>arg3</tt>, and so forth. For example:
  721. </p>
  722. <div class="code">
  723. <pre>
  724. %feature("action") Foo::bar {
  725. ...
  726. result = arg1-&gt;bar(arg2, arg3, etc.);
  727. ...
  728. }
  729. </pre>
  730. </div>
  731. <p>
  732. Given the potential to shoot yourself in the foot, it is probably easier to reconsider your
  733. design or to provide an alternative interface using a helper function than it is to create a
  734. fully general wrapper to a varargs C++ member function.
  735. </p>
  736. <H2><a name="Varargs_nn10"></a>13.9 Discussion</H2>
  737. <p>
  738. This chapter has provided a number of techniques that can be used to address the problem of variable length
  739. argument wrapping. If you care about portability and ease of use, the <tt>%varargs</tt> directive is
  740. probably the easiest way to tackle the problem. However, using typemaps, it is possible to do some very advanced
  741. kinds of wrapping.
  742. </p>
  743. <p>
  744. One point of discussion concerns the structure of the libffi examples in the previous section. Looking
  745. at that code, it is not at all clear that this is the easiest way to solve the problem. However, there
  746. are a number of subtle aspects of the solution to consider--mostly concerning the way in which the
  747. problem has been decomposed. First, the example is structured in a way that tries to maintain separation
  748. between wrapper-specific information and the declaration of the function itself. The idea here is that
  749. you might structure your interface like this:
  750. </p>
  751. <div class="code">
  752. <pre>
  753. %typemap(const char *fmt, ...) {
  754. ...
  755. }
  756. %feature("action") traceprintf {
  757. ...
  758. }
  759. /* Include some header file with traceprintf in it */
  760. %include "someheader.h"
  761. </pre>
  762. </div>
  763. <p>
  764. Second, careful scrutiny will reveal that the typemaps involving <tt>(...)</tt> have nothing
  765. whatsoever to do with the libffi library. In fact, they are generic with respect to the way in which
  766. the function is actually called. This decoupling means that it will be much easier to consider
  767. other library alternatives for making the function call. For instance, if libffi wasn't supported on a certain
  768. platform, you might be able to use something else instead. You could use conditional compilation
  769. to control this:
  770. </p>
  771. <div class="code">
  772. <pre>
  773. #ifdef USE_LIBFFI
  774. %feature("action") printf {
  775. ...
  776. }
  777. #endif
  778. #ifdef USE_OTHERFFI
  779. %feature("action") printf {
  780. ...
  781. }
  782. #endif
  783. </pre>
  784. </div>
  785. <p>
  786. Finally, even though you might be inclined to just write a hand-written wrapper for varargs functions,
  787. the techniques used in the previous section have the advantage of being compatible with all other features
  788. of SWIG such as exception handling.
  789. </p>
  790. <p>
  791. As a final word, some C programmers seem to have the assumption that
  792. the wrapping of variable length argument functions is an easily solved
  793. problem. However, this section has hopefully dispelled some of these
  794. myths. All things being equal, you are better off avoiding variable
  795. length arguments if you can. If you can't avoid them, please consider
  796. some of the simple solutions first. If you can't live with a simple
  797. solution, proceed with caution. At the very least, make sure you
  798. carefully read the section "A7.3.2 Function Calls" in Kernighan and
  799. Ritchie and make sure you fully understand the parameter passing conventions used for varargs.
  800. Also, be aware of the platform dependencies and reliability issues that
  801. this will introduce. Good luck.
  802. </p>
  803. </body>
  804. </html>