使用SWIG将C无符号字符指针绑定到Java ArrayList或集合结构 [英] Use SWIG to bind C unsigned char Pointer to Java ArrayList or Collection Structure
问题描述
如果我有一个C函数(请参见下文),该函数将无符号char指针返回到数组.您将如何指示SWIG绑定到getFoo()的Java ArrayList数据类型.我不确定是否可以使用ArrayList,也许是数组(在这种情况下为String []).我想使getFoo的Java返回类型尽可能通用,因为C getFoo可能返回int,double,char..etc等数组.
If I have a C function (see below) that returns a unsigned char pointer to an array. How would you instruct SWIG to bind to the Java ArrayList data type for getFoo(). I'm not sure an ArrayList is possible, maybe an array (String[] in this case). I want to keep the Java return type of getFoo as generic as possible since the C getFoo may return an array of int, double, char..etc.
unsigned char * getFoo(int32_t *length){
static unsigned char foo[44];
foo[0]='a';
foo[1]='b';
foo[2]='c';
foo[3]='d';
return foo;
}
推荐答案
The most generic answer is to expose the result as an unbouned C array in Java:
%module test
%include "carrays.i"
%array_class(unsigned char, ucArray);
unsigned char *getFoo();
这将生成一个名为ucArray
的类,该类具有针对特定索引的获取和设置.它是无限的,与C数组具有相同的语义,但轻巧且可用.由于它不受限制,因此您可以从Java调用未定义行为",并且它没有限制,因此无法用作Iterator
或Collection
.
This generates a class, called ucArray
, which has gets and sets for a specific index. It's unbounded, with the same semantics as C arrays, but lightweight and usable. Since it's not bounded you can invoke Undefined Behaviour from Java, and it has no bounds which makes it impossible to use as an Iterator
or Collection
.
如果您的数组以NULL/0终止,那么使用%extend
来实现Java Iterable
接口也相当容易,这是未经测试的粗糙示例:
If your array is NULL/0 terminated it would be reasonably easy to use %extend
to implement the Java Iterable
interface too, rough, untested example:
%typemap(javainterfaces) ucArray "java.lang.Iterable<Short>"
%typemap(javacode) ucArray %{
public java.util.Iterator<Short> iterator() {
return new java.util.Iterator<Short>() {
private int pos = 0;
public Short next() {
// Mmmm autoboxing!
return getitem(pos++);
}
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
// Check if we're at the end. A NULL/0 element represents the end
return getitem(pos) != 0;
}
};
}
%}
这需要在调用%array_class
宏之前进行.它说我们的ucArray
类将实现Iterable
,然后在iterator()
(Iterable
接口的唯一方法)方法中使用匿名内部类来实现该接口,以实现Iterator
接口.
This needs to go somewhere before the %array_class
macro gets called. It says that our ucArray
class will implement Iterable
and then implements that interface using an anonymous inner class in the iterator()
(the only method of the Iterable
interface) method to implement the Iterator
interface.
这篇关于使用SWIG将C无符号字符指针绑定到Java ArrayList或集合结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!