JNA:如何处理未知的结构? [英] JNA: how to deal with unkown structs?

查看:197
本文介绍了JNA:如何处理未知的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我没弄错的话, JNA Structure 依赖于相应Java类的公共字段构建结构,该类应扩展 Structure 。我的问题是我需要传递一个事先不知道声明的结构(让我们说它在运行时已知)。我只有一个 Object 的列表,C库期望它作为(对a)的结构。我还可以使用 Structure 类,还是我必须手工构建一个Memory对象,自己处理大小,对齐/打包?

If I'm not mistaken, a JNA Structure builds the struct by relying on the public fields of its corresponding Java class, which should extend Structure. My problem is that I need to pass a struct whose declaration is not known beforehand (let's say it's known at runtime). I just have a list of Objects, which the C library expects as a (reference to a) struct. Can I still use the Structure class or must I build a Memory object by hand, dealing with sizes, alignments/packing myself?

例如:

 /* native code */
 typedef struct mystruct {
     int x;
     float y;
 }  mystruct;

 void dosomething(mystruct * s) {
     s->y += s->x;
 }

在Java中:

 ...
 callFunctionWithSt("dosomething",
     new Object[]{Integer.valueOf(2),Float.valueOf(3.0)});
 ...

 void callFunctionWithSt(String funcName, Object[] structVals) {
     NativeLibrary nl = ...
     Pointer arg = ...  // or Memory ... or Structure
     // build structure
     for (Object objJava  : structVals) {
         valJna = convertFromJavaToJnaObject(objJava);
         // fill structure
     }
     f.invoke(arg);
 }

 Object convertFromJavaToJnaObject(Object) {
     // assume we know how to do this
 }


推荐答案

您仍然可以使用 Structure 。像这样定义你的接口方法:

You can still use Structure. Define your interface method like this:

interface SomeLib {
    public static final SomeLib INSTANCE =
        (SomeLib) Native.loadLibrary("SomeLib", SomeLib.class);

    Pointer getSomeStruct();
}

然后当你打电话时,你就这样做了:

Then when you call it, you just do this:

Pointer someValue = SomeLib.INSTANCE.getSomeStruct();
// do something here to determine what type it is
SpecificStructure struct = new SpecificStructure(someValue);

这篇关于JNA:如何处理未知的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆