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:
void add(int *x, int *y, int *r) {
*r = *x + *y;
}
By default, SWIG wraps this function exactly as specified and creates
an interface that expects pointer objects for arguments.
SWIG wraps a C pointer with a type wrapper class, for example, SWIGTYPE_p_int for an int*.
The only problem is how does one go about creating these objects from a Java program?
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);
}
and from Java you would use pointers like this:%include cpointer.i %pointer_functions(int, intp);
SWIGTYPE_p_int a = example.new_intp();
SWIGTYPE_p_int b = example.new_intp();
SWIGTYPE_p_int c = example.new_intp();
example.intp_assign(a,37);
example.intp_assign(b,42);
// Note that getCPtr() has package access by default
System.out.println(" a =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(a)));
System.out.println(" b =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(b)));
System.out.println(" c =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(c)));
// Call the add() function with some pointers
example.add(a,b,c);
// Now get the result
int res = example.intp_value(c);
System.out.println(" 37 + 42 =" + res);
// Clean up the pointers
example.delete_intp(a);
example.delete_intp(b);
example.delete_intp(c);
And in a Java program:%include "typemaps.i" void add(int *INPUT, int *INPUT, int *OUTPUT);
int[] r = {0};
example.sub(37,42,r);
System.out.println("Result =" + r[0]);
Needless to say, this is substantially easier although a bit unusual.
%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 ...