gpt4 book ai didi

java - 在 jna 中返回和访问结构对象数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:04 27 4
gpt4 key购买 nike

我在 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 your Structure 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);

编辑

名义上,你的结构看起来像这样(基于你的原生定义):

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com