JNA返回char *

时间:2013-06-26 14:42:08

标签: java jna

如何使用Check类型char *? (检查填写功能并包含文本> 500个字符或带文本的内存指针)

我有my_dll.dll。说明dll

int my_function(char* param1, struct answer* ans);

#pragma pack(1)
struct answer{
  int TType;                   //IN
  unsigned long Amount;   //IN
  char          Rcode   [2+1];  //OUT
  char          AMessage[16 ]; //OUT
  int           CType;              //OUT
  char*         Check;            //OUT
};

在Java中我有代码:

 public interface My_Dll extends Library {
        public static class answer extends Structure {
                    public static class ByReference extends answer 
                             implements Structure.ByReference {}

              public int  TType      = 0;                   
              public int  Amount     = 0;        
              public byte Rcode[]    = new byte[3]; //OUT: 
              public byte AMessage[] = new byte[16]; //OUT: 
              public int  CType      = 0;         //OUT: 
              public ??? Check;         //OUT: 
              protected List getFieldOrder() {
                      return Arrays.asList(new String[] {"TType", "Amount", 
                             "Rcode","AMessage", "CType","Check"});
              }
        }
        public int my_function(byte track2[], answer.ByReference ans);
  }

  public static void Start() {
      My_Dll test_dll = (My_Dll) Native.loadLibrary("my_dll", My_Dll.class);
      My_Dll.answer.ByReference aa = new My_Dll.answer.ByReference();
      //  In
      aa.Amount = 100;
      aa.TType =3;

      int result = test_dll.my_function(null,aa);
      //  OUT
      System.out.println("Result: "  + result);
      System.out.println("Rcode: "  + new String(aa.Rcode));
      System.out.println("Amessage: " + new String(aa.AMessage));
}

2 个答案:

答案 0 :(得分:1)

我尝试过的一件事是使用预先构造的byte数组,然后使用Native.toString(...)将其转换为Java String。例如,

byte[] windowText = new byte[SOME_CONSTANT];
user32.GetWindowTextA(hWnd, windowText, SOME_CONSTANT);
String wText = Native.toString(windowText).trim();

在上面的代码中,512作为我的SOME_CONSTANT运行良好,但您可能需要使用更大的常量。

答案 1 :(得分:1)

您的Check字段必须是指针类型。如果您将其声明为Pointer,则可以使用Pointer.getString(0)来提取String值。

如果由调用者来分配内存,可以使用com.sun.jna.Memory对其进行初始化;如果没有,您将需要释放结构中返回的内存以避免泄漏。