Reputation: 9827
I have a C function (composeKey) that has an input unsigned char* parameter ("key"). On the C side, "key" needs to be an empty 20 byte buffer structure. I'm assuming that a Java short array with a size of 20 would be the correct Java structure to pass composeKey's "key" parameter, but I'm unsure. Maybe a byte[20] is what i need. If that is correct, what SWIG Interface file modification is needed to generate the composeKey Java method with a short[] as input for the "key" parameter?
C Function:
int composeKey(const void* secret, int secret_len, unsigned char* key, int length);
Upvotes: 0
Views: 1313
Reputation: 88711
Java doesn't really distinguish between short[20]
and (e.g.) short[21]
in its type system. You can do something that's pretty sensible quite simply though, by making the fact that the length of key
is always 20 obvious to SWIG:
%module test
%include "arrays_java.i"
int func(unsigned char key[20]);
This can work even without changing the actual signature of your function directly - SWIG can wrap that, but have the wrapped code call a function that still takes unsigned char*
quite sensibly:
%module test
%{
#include "header.h"
// fine even if it's func(unsigned char *key) in the header.
%}
%include "arrays_java.i"
int func(unsigned char key[20]);
If you call func
from Java with an inappropriately sized array you'll get an IndexOutOfBoundsException
exception thrown for you automatically by the code that SWIG generates.
In this specific case "arrays_java.i"
provides a suitable typemap already. In the more general case this works by providing SWIG with a typemap for unsigned char [ANY]
(literally write ANY
in SWIG typemap syntax). This then gets instantiated for specific values in place of ANY
(sort of like a template in C++), you can then access the specific value of ANY
in your typemap using $1_size
and supply code that the sizes gets filled in to look (some JNI details omitted for brevity) roughly like:
if (GetArrayLength(arg) != $1_size) {
// Code to throw a Java Exception ...
Which then in the generated wrapper becomes:
if (GetArrayLength(arg) != 20) {
// Code to throw a Java Exception ...
Upvotes: 1