SWIG指针和Java数组 [英] SWIG pointers and Java arrays
问题描述
SWIG文档说明了C语言中各种输入类型的方式,例如:
void spam1(Foo *x); // Pass by pointer
void spam2(Foo &x); // Pass by reference
void spam3(Foo x); // Pass by value
void spam4(Foo x[]); // Array of objects
...在Java中都将采用单一类型的参数,就像这样:
Foo f = new Foo(); // Create a Foo
example.spam1(f); // Ok. Pointer
example.spam2(f); // Ok. Reference
example.spam3(f); // Ok. Value.
example.spam4(f); // Ok. Array (1 element)
类似地,对于C中的返回类型:
Foo *spam5();
Foo &spam6();
Foo spam7();
...这三个函数都将返回一个指向某个Foo对象的指针,该对象将被分配给Java对象变量,最后一个函数需要分配一个值类型,Java垃圾回收将在释放时处理该值类型. /p>
但是,假设spam5()返回一个指向数组的指针.在Java中,我必须使用数组语义来访问各个元素,但是我认为我不能做到这一点:
Foo foo[] = spam5();
我什至都不认为编译器会接受对(Foo [])的强制转换,那么这在SWIG中如何工作?
此问题没有简单或自动的解决方案.相信我,我看了.
问题是SWIG不知道您要返回的数组应该有多大,因此它无法生成Java数组.您也不能提供大小作为函数的参数(那样粗)-类型图不能那样工作.
在一般情况下,您必须编写另一个包装器函数,该函数将C数组和长度作为out参数,并使用类型映射将这两个参数转换为Java数组.或者,如果您不介意使用carrays.i,则可以跳过第二步,而直接从Java直接使用C数组.
The SWIG documentation explains how a variety of input types in C, like this:
void spam1(Foo *x); // Pass by pointer
void spam2(Foo &x); // Pass by reference
void spam3(Foo x); // Pass by value
void spam4(Foo x[]); // Array of objects
... would all take a single type of argument in Java, like this:
Foo f = new Foo(); // Create a Foo
example.spam1(f); // Ok. Pointer
example.spam2(f); // Ok. Reference
example.spam3(f); // Ok. Value.
example.spam4(f); // Ok. Array (1 element)
Similarly, for return types in C:
Foo *spam5();
Foo &spam6();
Foo spam7();
... all three functions will return a pointer to some Foo object that will be assigned to a Java object variable, the final one requiring an allocation of a value type that the Java garbage collection will take care of upon release.
But suppose spam5() returns a pointer to an array. In Java, I have to use array semantics to access the individual elements, but I don't think that I can just do this:
Foo foo[] = spam5();
I don't even think the compiler would accept a cast to (Foo[]), so how does this work in SWIG?
This problem does not have a simple or automatic solution. Believe me, I looked.
The problem is that SWIG doesn't know how big the array you're returning is supposed to be, so it can't generate a Java array. You can't supply the size as an argument to the function, either (gross as that would be) - typemaps don't work that way.
In the general case you have to write another wrapper function, which takes a C array and a length as an out parameter, and use a typemap to turn those two parameters into a Java array. Or, if you don't mind using carrays.i, you can skip the second step and just work with C arrays directly from Java.
这篇关于SWIG指针和Java数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!