【问题标题】:JAVA-JNA : I can't modify a structure field throughout a callback functionJAVA-JNA:我无法在整个回调函数中修改结构字段
【发布时间】:2020-05-08 23:03:50
【问题描述】:

我对 JNA 回调有疑问。在我的 JAVA 程序中,我使用了一个将由本机库调用的函数指针。这个函数指针是:

public int callback(S_CODELINE_INFO codelineInfo)
{
    try
    {
    String codeline=new String(codelineInfo.CodelineRead);
    System.out.println("Codeline document : "+codeline); // Reading from DLL is ok

    // Set field Sorter (JAVA --> DLL)
    codelineInfo.writeField("Sorter", 9); // Writing is KO. The sorted field (sort type) is always equal to 0

    }catch(Exception exp)
    {

    exp.printStackTrace();
    }

    return 0;
}

_CODELINE_INFO 结构:

public class S_CODELINE_INFO extends Structure
{
   /************** Parameters compiled from LS500.dll ************************/

    // Size of the struct
    public short Size;  

    // Progessive document number
    public NativeLong NrDoc;

    // Codeline returned    
    public byte[] CodelineRead=new byte[39];    

    // Length of the codeline
    public short NrBytes;   

    // Reserved for future use
    public NativeLong Reserved;                     

    /****************** Parameters compiled from Application *********************/

    // Sorter where put the document
    public short Sorter;    

    // Set from application NORMAL or BOLD
    public byte FormatString;       

    // String to print rear of the document
    public String StringToPrint;

    public S_CODELINE_INFO()
    {
        super();
    }

    @Override
    protected List<String> getFieldOrder() 
    {
        return Arrays.asList(new String[]{
            "Size", "NrDoc", "CodelineRead", "NrBytes", "Reserved", "Sorter","FormatString", "StringToPrint"        
        });
    }

    public static class ByReference extends S_CODELINE_INFO implements Structure.ByReference{};

}

【问题讨论】:

  • 问题是什么?发生了什么错误?
  • 我无法修改字段排序器。本机库始终接收 0 值
  • Sorter 字段是 Java 应用程序设置的字段,供本地库使用
  • 我无法更改排序器字段的值。有什么办法解决这个问题吗?
  • 您的问题不到 24 小时。可能20个看过的人都不知道怎么回答。为了让更多的 JNA 专家,包括可能不经常访问这里的 JNA 项目维护人员,您的问题可以在JNA Mailing List. 上提问

标签: java callback jna


【解决方案1】:

你正在修改结构,只是没有按照你想要的方式。

JNA 的 Structure 类将其 Java 字段映射到 C struct 等效的本机内存中的适当偏移量。

在这种情况下,按照您定义结构的方式,您正在尝试写入Sorter 字段,这是一个short(2 字节)字段,距离结构开头的偏移量为 51 个字节。

但是,这可能不是 Sorter 在本机端的位置。我不确定你的39 来自哪里,但是我在网上看到的本机代码有:

char CodelineRead[CODE_LINE_LENGTH]; // Codeline returned

定义该值:

#define CODE_LINE_LENGTH 256 // Max length of returned codeline

因此在字节 51-52 处写入不起作用,因为您在本机端的 CodeLineRead 数组的中间写入。

【讨论】:

  • codelineInfo.writeField("Sorter",(short) 2) 的问题相同。在 DLL 日志中,我有 00:33:52.768 2020 - 2696 - ReadCodelineAndSort_Ls5xx - infoCodeline.Sorter = 0
  • 我根据 CodeLineRead 数组的错误长度更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多