用SWIG array_class包装字节数组数据

时间:2012-02-18 00:37:37

标签: swig

我有一个C函数,它返回一个unsigned char *,它可以是指向字节数组的指针(表示File..etc的二进制数据)或指向字符数组的指针。我目前正在使用SWIG %array_class,它包装所有返回unsigned char指针的C函数,并创建一个Java数组实用程序(SampleArrayUtil.java)来处理Java端的填充和检索。

我的问题是我还使用unsigned char *使用:%apply char * { unsigned char * };来包装,以便在Java端获得一个字符串数组。当我得到二进制数据时,我不想包装unsigned char *返回值(使用%apply char * { unsigned char * };),我想在Java端拥有字节数组。我正在考虑创建另一个C函数来处理二进制数据,但我不确定如何包装这个新函数,因为它还将返回unsigned char *(参见getValueFromRowAsByteArray

C函数:

unsigned char * getValueFromRowAsStringArray(struct result_row *row, attribute_type type, int32_t *len)

unsigned char * getValueFromRowAsByteArray(struct result_row *row, attribute_type type, int32_t *len)
//*row* input param with data results, *type* input enum type for the data type being requested and *len* is an output param that contains the length of the data being returned.

用于包装C函数的SWIG接口文件返回unsigned char *(char数组):

%module Sample
%include "typemaps.i"
%include "stdint.i"
%include "arrays_java.i"
%include "carrays.i"
%array_class(unsigned char, SampleArrayUtil);
%{
#include "C_API.h"
%}
%apply char * { unsigned char * };
%include "C_API.h"

1 个答案:

答案 0 :(得分:2)

您可以通过至少两种方式将不同类型的地图应用于不同地方的相同类型。

首先,您可以使用%apply%clear更改有效的类型地图,例如:

%module test

%include "stdint.i"

%apply intptr_t { unsigned char * };
unsigned char * test1();

%apply char * { unsigned char * };
unsigned char * test2();

%clear unsigned char *;
unsigned char * test3();

根据活动类型映射,在Java中使用不同的返回类型提供三个函数。

其次,您也可以编写更具体的类型图,例如:

%apply long long { unsigned char * test4 };
%apply char * { unsigned char * test5 };
unsigned char * test4();
unsigned char * test5();

仅分别适用于test4test5 - 它与类型和函数名称匹配。在Java中,这导致:

  public static long test4() {
    return testJNI.test4();
  }

  public static String test5() {
    return testJNI.test5();
  }

对于参数,您可以类似地匹配函数签名中的类型和参数名称。