Convert a member of a type structure signed by char * to an array of bytes in Java (byte []) using SWIG

I am trying to convert a member of a structure of type signed by char * to an array of bytes in Java. I have the following structure:

typedef struct { signed char * content; int contentLength; } Foo; 

I tried this:

 %typemap(jni) signed char *content [ANY] "jbyteArray" %typemap(jtype) signed char *content [ANY] "byte[]" %typemap(jstype) signed char *content [ANY] "byte[]" %typemap(javaout) signed char *content [ANY] { return $jnicall; } %typemap(memberin) int contentLength [ANY] { int length=0; $1 = &length; } %typemap(out) signed char * content [ANY] { $result = JCALL1(NewByteArray, jenv, length); JCALL4(SetByteArrayRegion, jenv, $result, 0, length, $1); } 

But there is no result. The getContent Foo method has the following signature:

 SWIGTYPE_p_signed_char getContent(); 

I want this method to return a byte []. Is there a solution?

+4
source share
1 answer

This is very close to what you want. You do not want [ANY] , since the size of the array is not "fixed" in C (it is specified by int , but is not part of its type).

You can do your typography with:

 %module test %typemap(jni) signed char *content "jbyteArray" %typemap(jtype) signed char *content "byte[]" %typemap(jstype) signed char *content "byte[]" %typemap(javaout) signed char *content { return $jnicall; } %typemap(out) signed char * content { $result = JCALL1(NewByteArray, jenv, arg1->contentLength); JCALL4(SetByteArrayRegion, jenv, $result, 0, arg1->contentLength, $1); } // Optional: ignore contentLength; %ignore contentLength; %inline %{ typedef struct { signed char * content; int contentLength; } Foo; %} 

I might be missing something, but I donโ€™t see a better way to get a "self" interpreter from inside this map than this - arg$argnum does not work, and $self does not matter. There are no other types that will be applied to this function that will help.

(Note that you probably also want to write memberin for signed char * content or make it immutable. I would also tempt %ignore the contentLength member).

+3
source

All Articles