Use SWIG to bind C unsigned char Pointer to a Java ArrayList or collection structure

If I have a C function (see below) that returns an unsigned char pointer to an array. How would you instruct SWIG to bind to the Java data type ArrayList for getFoo (). I'm not sure if an ArrayList is possible, maybe an array (String [] in this case). I want to keep the return type of Java getFoo as general as possible, since C getFoo can return an array from int, double, char, etc.

unsigned char * getFoo(int32_t *length){ static unsigned char foo[44]; foo[0]='a'; foo[1]='b'; foo[2]='c'; foo[3]='d'; return foo; } 
+1
source share
1 answer

The most common answer is to show the result as an unbouned C array in Java:

 %module test %include "carrays.i" %array_class(unsigned char, ucArray); unsigned char *getFoo(); 

This generates a class called ucArray , which gets and sets for a specific index. It is unlimited, with the same semantics as C-arrays, but easy and convenient. Since it is not limited, you can call Undefined Behavior from Java, and it has no boundaries, which makes it impossible to use as an Iterator or Collection .

If your array is NULL / 0 complete, it would be wise to just use %extend to implement the Java Iterable interface, a crude, unchecked example:

 %typemap(javainterfaces) ucArray "java.lang.Iterable<Short>" %typemap(javacode) ucArray %{ public java.util.Iterator<Short> iterator() { return new java.util.Iterator<Short>() { private int pos = 0; public Short next() { // Mmmm autoboxing! return getitem(pos++); } public void remove() { throw new UnsupportedOperationException(); } public boolean hasNext() { // Check if we're at the end. A NULL/0 element represents the end return getitem(pos) != 0; } }; } %} 

This needs to be moved somewhere before the %array_class macro is called. It says that our ucArray class implements Iterable , and then implements this interface using the anonymous inner class in iterator() (the only Iterable interface method) to implement the Iterator interface.

+1
source

Source: https://habr.com/ru/post/922851/


All Articles