Reputation: 97
I want to wrap a struct containing a fixed size array of unsigned char to byte[] in Java. My interface file currently looks like this:
%module example
%include "arrays_java.i"
struct myStruct
{
unsigned char data[1024];
int len;
};
The java proxies created contain get and set methods which take and return a short[].
Is there a way and if yes, what is the easiest way I can force SWIG to generate java proxies using byte[] instead of short[]?
I don't want to change the struct in any way. This is just a simplified example of a very large interface I have to wrap that I cannot change.
I am aware of the fact that byte in java is signed and doesn't cover the range of unsigned char in C, but for passing data around it is much more convenient than dealing with short[] or the wrapper created using array_class defined in carrays.i which eventually offers getItem and setItem methods that in turn take or return short.
So my question is just about if I can force swig somehow (maybe with some typemap) to treat unsigned char data[1024] like char[1024] in that it maps to a byte[] in java.
Upvotes: 2
Views: 1568
Reputation: 88711
We can force SWIG to treat your unsigned char arrays as signed char arrays for the purpose of SWIG wrapping only using %apply
. For example using:
%module example
%include "arrays_java.i"
%apply signed char[ANY] { unsigned char[ANY] };
struct myStruct
{
unsigned char data[1024];
int len;
};
Will force this to happen for all unsigned char
arrays of any (known) size. (Think of %apply
as typemap copy and paste)
You could also write:
%apply signed char[ANY] { unsigned char data[ANY] };
Or:
%apply signed char[ANY] { unsigned char data[1024] };
which would only apply to arrays of type unsigned char
of any size, or size 1024 respectively.
As a handy tip: I figured out exactly which typemaps I wanted to match on for the %apply
by calling SWIG with the '-debug-tmsearch' flag which showed originally:
....
test.i:8: Searching for a suitable 'jni' typemap for: unsigned char data[1024]
Looking for: unsigned char data[1024]
Looking for: unsigned char [1024]
Looking for: unsigned char data[ANY]
Looking for: unsigned char [ANY]
Using: %typemap(jni) unsigned char [ANY]
....
which shows you what typemaps will apply in what order of precedence for every typemap used by your interface.
Upvotes: 3