gpt4 book ai didi

java - 结构内部的 JNA 结构

转载 作者:行者123 更新时间:2023-12-01 09:37:20 25 4
gpt4 key购买 nike

我对 JNA 编程很陌生。我有一个 native 代码如下

int Data(int Number, aaa *Data, int* error);

typedef struct {
uint8 Storage;
LStr path;
int32 chart;
int32 strt;
LStr val;
int32 timedata;
} aaa;

typedef struct {
int32 cnt; /*num of bytes that follow*/
uChar str[1];
} LStrval, *LStrPtr, **LStr;

如何使用 JNA 从 Java 调用此 native 函数。我尝试了几种选择,但没有得到结果。我尝试过的选项之一如下。

接口(interface)函数

public int SetStorage_Data(int num,Storage_Data.ByReference data, Pointer error);

public class Storage_Data extends Structure{
public static class ByReference extends Storage_Data implements Structure.ByReference {}

public byte storage;
public Stringtype.ByReference savepath;
public int chart;
public int strt;
public Stringtype.ByReference val;
public int timedata;

@Override
protected List getFieldOrder() {
return Arrays.asList("storage", "savepath","chart",
"strt","val","timedata");
}
}



public class Stringtype extends Structure{
public static class ByReference extends Stringtype implements Structure.ByReference {

public ByReference(int buffersize) {
super(buffersize);
// TODO Auto-generated constructor stub
}}

public int count;
public byte[] str;

public Stringtype(int buffersize) {
str = new byte[buffersize];
count = str.length;
allocateMemory();
}

@Override
protected List getFieldOrder() {
return Arrays.asList("count", "str");
}
}

以及 Java 调用

InjectionAnalyzerInterfaces.Storage_Data.ByReference storagedata = new InjectionAnalyzerInterfaces.Storage_Data.ByReference();

int len= string.length;
InjectionAnalyzerInterfaces.Stringtype.ByReference savepath = new InjectionAnalyzerInterfaces.Stringtype.ByReference(len);

byte[] stringbyte = string.getBytes();
System.arraycopy(stringbyte, 0, savepath.str, 0, bytes);
storagedata.savepath = savepath;
storagedata.chart = 1;
storagedata.strt =1;
String temp= "all";
byte[] strtbyte = temp.getBytes();
int dd = strtbyte.length;
InjectionAnalyzerInterfaces.Stringtype.ByReference stra = new InjectionAnalyzerInterfaces.Stringtype.ByReference(dd);
System.arraycopy(strtbyte, 0, stra.str,0, dd);
storagedata.strt = stra;


storagedata.tdata = 0;

Pointer error = new Memory(5);

int status1 = lib.Set_Config_Storage_Data(deviceNumber, storagedata, error);

请帮助我。预先感谢您

最佳答案

在定义 LStrVal 时,您需要初始化原始数组字段,以便 JNA 知道要分配多少内存(至少在开始时):

public byte str = new byte[1];

您需要重写 Structure.read() 来做正确的事情,并提供一个基于 Pointer 的构造函数以在从 native 内存初始化后读取:

public void read() {
count = (int)readField("count");
str = new byte[count];
super.read();
}

public LStr(Pointer p) {
super(p);
read();
}

最后,您的包含结构具有 struct** 字段(不知道为什么),您必须将其映射到 Pointer,并提供一个方便的函数来实际转换为您想要的结构:

public Pointer savepath;
public LStr getSavepath() {
return savepath != null ? new LStr(savepath.getPointer(0)) : null;
}

关于java - 结构内部的 JNA 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38764646/

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