JNA结构字段值错误

JNA wrong structure field values

本文关键字:错误 字段 结构 JNA      更新时间:2023-10-16

我正在围绕JNA适配器"twain.h"跳舞——几乎做到了,但在获得扫描仪功能方面仍然存在一些问题。有一个原始的基因:

typedef unsigned short TW_UINT16, FAR *pTW_UINT16;
typedef unsigned long  TW_UINT32, FAR *pTW_UINT32;
typedef struct {
   TW_UINT16  ItemType;
   TW_UINT32  MinValue;     /* Starting value in the range.           */
   TW_UINT32  MaxValue;     /* Final value in the range.              */
   TW_UINT32  StepSize;     /* Increment from MinValue to MaxValue.   */
   TW_UINT32  DefaultValue; /* Power-up value.                        */
   TW_UINT32  CurrentValue; /* The value that is currently in effect. */
} TW_RANGE, FAR * pTW_RANGE;

这是我的地图(thnx JN曝气器)

public static class TW_RANGE extends Structure {
        /** C type : TW_UINT16 */
        public short ItemType;
        /** C type : TW_UINT32 */
        public NativeLong MinValue;
        /** C type : TW_UINT32 */
        public NativeLong MaxValue;
        /** C type : TW_UINT32 */
        public NativeLong StepSize;
        /** C type : TW_UINT32 */
        public NativeLong DefaultValue;
        /** C type : TW_UINT32 */
        public NativeLong CurrentValue;
        public TW_RANGE() {
            super();
        }
        protected List<? > getFieldOrder() {
            return Arrays.asList("ItemType", "MinValue", "MaxValue", "StepSize", "DefaultValue", "CurrentValue");
        }
}

当我向扫描仪询问这个实体时,扫描仪会向我发送回填充的对象,但当我通过创建它时

new TW_RANGE(pointer)

它还给我一些有线的东西

TwaindsmLibrary$TW_RANGE(native@0x157c000c) (22 bytes) {
  short ItemType@0=870
  NativeLong MinValue@2=1572916
  NativeLong MaxValue@6=5500
  NativeLong StepSize@a=2097152
  NativeLong DefaultValue@e=5500
  NativeLong CurrentValue@12=2621440
}
  1. 我该如何解读这些价值观
  2. 我可以转储本机结构并用一些工具进行分析吗?看过Pointer.dump,但它需要转储值的大小,我如何才能得到指针下结构的大小
必须调用

Structure.read()才能将本机内存复制到JNA Structure字段中。

最简单的方法是确保从TW_RANGE(Pointer)构造函数调用Structure.read()作为最后一条语句。

JNA通常在进行函数调用时自动调用Structure.read()/write()。它有意在Structure构造函数中执行而不是,让程序员决定执行同步的最佳点(如果有的话)。

我搞定了!经过对C++代码的少量调试,我发现(TW_RANGE*)指针和Java一样一团糟。但是(TW_RANGE**)指针的作用就像一个符咒。所以

new TW_RANGE(pointer.getPointer(0))

[掌声]这个解决方案导致我出现随机内存访问错误。我应该使用Twain原生的MemAllocate/Lock/Free函数,它从给定的指针返回正确的值。