This example illustrates a couple of techniques for handling simple pointers in SWIG. The prototypical example is a C function that operates on pointers such as this:
By default, SWIG wraps this function exactly as specified and creates an interface that expects pointer objects for arguments. The only problem is how does one go about creating these objects from a Java program?void add(int *x, int *y, int *r) { *r = *x + *y; }
By default SWIG wraps a C pointer with a Java long. Now in a Java program you would do this:int *new_int(int ivalue) { int *i = (int *) malloc(sizeof(ivalue)); *i = ivalue; return i; } int get_int(int *i) { return *i; } void delete_int(int *i) { free(i); }
long a = new_int(37); long b = new_int(42); long c = new_int(0); add(a,b,c); int r = get_int(c); System.out.println("Result =" + r); delete_int(a); delete_int(b); delete_int(c);
%include "pointer.i"
String a = ptrcreate("int",37); String b = ptrcreate("int",42); String c = ptrcreate("int"); add(a,b,c); int r = ptrvalue(c); System.out.println("Result =" + r); ptrfree(a); ptrfree(b); ptrfree(c);The advantage to using the pointer library is that it unifies some of the helper functions behind a common set of names. For example, the same set of functions work with int, double, float, and other fundamental types.
And in a Java program:%include "typemaps.i" void add(int *INPUT, int *INPUT, int *OUTPUT);
Needless to say, this is substantially easier.int[] r = {0}; example.sub(37,42,r); System.out.println("Result =" + r[0]);
%include "typemaps.i" %apply int *INPUT {int *x, int *y}; %apply int *OUTPUT {int *r}; void add(int *x, int *y, int *r); void sub(int *x, int *y, int *r); void mul(int *x, int *y, int *r); ... etc ...