我是新手JNA开发人员所以如果这个问题很简单,请原谅我,但是我正在努力反对处理C-lang结构对象,包括带有JNA的float数组。目前我遇到了编译错误。
我认为问题是初始化并将FloatByReference实例(mys.Weights
)分配给mystruct类实例(mys
)的错误方法,并且认为不应修改下面的Java代码,因为JNAerator会自动生成它
我的C代码:
typedef struct
{
int n;
float *Weights;
} mystruct;
void testfunc(mystruct* mys){
printf(mys->Weights[0]);
}
public interface CLibrary extends Library {
public static final String JNA_LIBRARY_NAME = "test";
public static final NativeLibrary JNA_NATIVE_LIB = NativeLibrary.getInstance(CLibrary.JNA_LIBRARY_NAME);
public static final CLibrary INSTANCE = (CLibrary)Native.loadLibrary(CLibrary.JNA_LIBRARY_NAME, CLibrary.class);
和Java:
public interface CLibrary extends Library {
public static final String JNA_LIBRARY_NAME = "test";
public static final NativeLibrary JNA_NATIVE_LIB = NativeLibrary.getInstance(CLibrary.JNA_LIBRARY_NAME);
public static final CLibrary INSTANCE = (CLibrary)Native.loadLibrary(CLibrary.JNA_LIBRARY_NAME, CLibrary.class);
public static class mystruct extends Structure {
public int n;
public FloatByReference Weights;
protected List<? > getFieldOrder() {
return Arrays.asList("n", "Weights");
}
public mystruct(int n, JnaeratorTestLibrary.feature_t.ByReference Features, FloatByReference Weights) {
super();
this.n = n;
this.Features = Features;
this.Weights = Weights;
}
public mystruct(Pointer peer) {
super(peer);
}
public static class ByReference extends mystruct implements Structure.ByReference {
};
public static class ByValue extends mystruct implements Structure.ByValue {
};
};
void testfunc(CLibrary.mystruct mys);
}
public static void main(String[] args) {
mystruct mys = new mystruct();
mys.n = 10;
mys.Weights = new FloatByReference();
// Compile error raises.
mys.Weights = new float[4]; mys.Weights[0] = 1.0;
testfunc(mys);
}
编译错误消息:
类型不匹配:无法从float []转换为FloatByReference
答案 0 :(得分:1)
使用Pointer
,然后使用Pointer.getFloatArray(0, n)
提取所需的数据。
在将内存分配给结构字段之前,您需要分配Memory
并使用Memory.write()
将Java原始浮点数组写入本机内存。
FloatByReference
基本上是指向一个分配的float的指针。 JNAerator根本无法区分指向单个float的指针和指向float的缓冲区的指针(没有一些额外的上下文的人也不能)。