4

I'm trying to convert a member of structure of type signed char * to byte array in Java. I've the following structure:

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

I've 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 isn't a result. The method getContent of the Foo have the following signature:

SWIGTYPE_p_signed_char getContent();

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

1 Answer 1

3

That's pretty close to what you want. You don't want the [ANY] since the size of the array is not "fixed" in C (it's specified by an int, but that's not part of its type).

You can make your typemap work 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 here, but I can't see a better way of getting hold of the "self" pointer from within an out typemap than this - arg$argnum doesn't work and neither does $self. There aren't any other typemaps that get applied to this function that would help.

(Note you probably also want to write a memberin for signed char * content or make it immutable. I'd be tempted to %ignore the contentLength member entirely too).

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much for your help. How can I ignore the contentLength ?
@SvetoslavMarinov - I added the easiest way into my example
Thank you again it works. I've tried this before I ask you but maybe I haven't put it on the right place.
@SvetoslavMarinov it needs to be before the definition is seen.
I'm sorry for the late question but can you give us an example of how to create memberin for the signed char * content? I'll be very helpful for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.