简体   繁体   English

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

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

I'm trying to convert a member of structure of type signed char * to byte array in Java. 我正在尝试将signed char *类型的结构成员转换为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: Foo的方法getContent具有以下签名:

SWIGTYPE_p_signed_char getContent();

I want this method to returns byte[]. 我希望这个方法返回byte []。 Is there a solution? 有解决方案吗?

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). 您不需要[ANY]因为数组的大小不是在C中“固定”(它由int指定,但这不是其类型的一部分)。

You can make your typemap work with: 您可以使您的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;
%}

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 . 我可能在这里遗漏了一些东西,但是我看不出更好的方法是从out类型arg$argnum中获取“self”指针而不是这个 - arg$argnum不起作用,也不是$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). (注意,您可能还想为signed char * content编写一个memberin或使其成为不可变的。我很想完全%ignore contentLength成员)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM