使用SWIG将signed char *类型的结构成员转换为Java(byte [])中的字节数组

时间:2012-08-15 08:13:58

标签: java c swig

我正在尝试将signed char *类型的结构成员转换为Java中的字节数组。我有以下结构:

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

我试过这个:

%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);
}

但没有结果。 Foo的方法getContent具有以下签名:

SWIGTYPE_p_signed_char getContent();

我希望这个方法返回byte []。有解决方案吗?

1 个答案:

答案 0 :(得分:3)

这非常接近你想要的。您不需要[ANY],因为数组的大小在C中没有“固定”(由int指定,但这不是其类型的一部分。)

您可以使用以下内容使用typemap:

%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;
%}

我可能在这里遗漏了一些东西,但是我看不出更好的方法是从out类型映射中获取“self”指针而不是这样 - arg$argnum不起作用,$self也不起作用signed char * content 1}}。没有任何其他类型地图可以应用于此功能,这将有所帮助。

(请注意,您可能还想为%ignore写一个memberin或使其成为不可变的。我也很想contentLength {{1}}成员。

相关问题