我有一个包含 C 中的一些 char 指针的结构:
struct inputsheet
{
char* TestCaseID[MAX_TEST_CASES];
char* Description[MAX_TEST_CASES];
};
我有一个返回结构对象数组的函数:
struct inputsheet* getapi(char *docname);
现在我想在 Java 中使用它。我该如何处理这个结构对象数组?我能够处理单个对象,但不能处理数组。
对于单个对象,我的 C 代码在这里:
public class str3 extends com.sun.jna.Structure implements com.sun.jna.Structure.ByReference {
public Pointer a1;
public Pointer b2;
public Pointer c3[]=new Pointer[10];
}
访问它:
str2 s2=CLibrary.INSTANCE.parseid(xmlFile1);
for(Pointer p1:s2.testCaseID) {
if(p1!=null)
{
System.out.println(p1.getString(0));
}
}
编辑
\\c code
struct str3{
char *a;
char *b;
char *ab[10];
}
\\jna implementation
package parser;
import com.sun.jna.Pointer;
public class str3 extends com.sun.jna.Structure implements com.sun.jna.Structure.ByReference{
public Pointer a1;
public Pointer b2;
public Pointer c3[]=new Pointer[10];
}
\\calling it
import com.sun.jna.Native;
import com.sun.jna.Pointer;
class ab{
interface CLibrary extends Library{
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("chardll",
CLibrary.class);
str3 getStruct();
}
public static void main(String[] args) {
int size = 5;
str3 a=CLibrary.INSTANCE.getStruct();
str3[] ab=(str3[])a.toArray(size);
System.out.println(ab[0].a1.getString(0));
}
}
它给出了垃圾值作为输出,我必须更新我的代码才能获得正确的输出..
最佳答案
来自 javadoc :
Returning an Array of struct
Declare the method as returning a Structure of the appropriate type, then invoke
Structure.toArray(int)
to convert to an array of initialized structures of the appropriate size. Note that yourStructure
class must have a no-args constructor, and you are responsible for freeing the returned memory if applicable in whatever way is appropriate for the called function.// Original C code struct Display* get_displays(int* pcount); void free_displays(struct Display* displays); // Equivalent JNA mapping Display get_displays(IntByReference pcount); void free_displays(Display[] displays); ... IntByReference pcount = new IntByReference(); Display d = lib.get_displays(pcount); Display[] displays = (Display[])d.toArray(pcount.getValue()); ... lib.free_displays(displays);
编辑
名义上,您的结构将如下所示(基于您的 native 定义):
class inputsheet extends Structure {
public Pointer[] TestCaseID = new Pointer[MAX_TEST_CASES];
public Pointer[] Description = new Pointer[MAX_TEST_CASES];
}
public inputsheet getapi(String docname);
int size = ...; // whatever you do to figure out the size of your returned array
inputsheet sheet = INSTANCE.getapi("some-doc");
inputsheet[] sheets = (inputsheet[])sheet.toArray(size);
如果调用者不需要写入 inputsheet
字段,则应使用 String
而不是 Pointer
。
关于java - 返回和访问 jna 中结构对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15430260/