gpt4 book ai didi

java - 从 C 获取结构体(通过引用)

转载 作者:行者123 更新时间:2023-12-01 11:54:29 24 4
gpt4 key购买 nike

假设我有下一个 C 代码片段,并且我想使用 JNA 从 Java 调用它。

typedef struct {
int bit_a;
int bit_b;
} * bit_handle;

bit_handler handle_open(const char *name, int prop);

出于这样的目的,我编写了下一个 Java 代码片段:

Java代码:

 public interface BitLibrary extends Library {
BitLibrary INSTANCE = (BitLibrary) Native.loadLibrary("bitlibrary", BitLibrary.class);
Pointer handler_open(char* name, int prop);
}

它工作得很好,但我想通过引用检索 BitHandle 对象(请参阅下面的实现),而不是指针,因为前面的 C 代码中的 bit_handle 是一个指针。我怎么能这么做呢?我尝试过类似 this example 的东西但我得到一个 ClassCastException ,它说 java.lang.reflect.Field 无法转换为 java.lang.Comparable ,我有点无能为力,因为从逻辑角度来看应该可行,但事实并非如此。我错过了什么吗?

BitHandle 实现:

    public static class BitHandle extends Structure {
public int bit_a;
public int bit_b;

public BitHandle(Pointer peer){
super(peer);
}

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected List<?> getFieldOrder() {
List fieldList = new ArrayList(super.getFieldList());
fieldList.addAll(Arrays.asList("bit_a", "bit_b"));
return fieldList;
}

}

最佳答案

已找到解决方案,感谢@user2864740的建议。关键是忽略 getFieldOrder() javadoc 并按如下方式实现它:

public class BitTest {

public interface BitLibrary extends Library {
BitLibrary INSTANCE = (BitLibrary) Native.loadLibrary("bit", BitLibrary.class);

public static class BitHandle extends Structure {
public int bit_a;
public int bit_b;
public static class ByReference extends BitHandle implements Structure.ByReference {}


@Override
protected List getFieldOrder() {
List<String> fieldList = new ArrayList<>();
fieldList.addAll(Arrays.asList("bit_a", "bit_b"));
return (List) fieldList;
}

}


BitHandle.ByReference bit_open(String drivername, int lun);

}

public static void main(String[] args) {
BitLibrary.BitHandle.ByReference pointer = BitLibrary.INSTANCE.Bit_open("CIBM_LINUX", 0);
}

}

关于java - 从 C 获取结构体(通过引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28547996/

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