简体   繁体   English

如何在jna中获得指向结构数组的指针

[英]how to get a pointer to an array of structure in jna

I really want to get a pointer to an array of structures, just like in C, using Java jna. 我真的想使用Java jna来获得指向结构数组的指针,就像在C中一样。 I want to access the EnumPrinters() function, and here are the parameters to it: 我想访问EnumPrinters()函数,这是它的参数:

BOOL EnumPrinters(
_In_ DWORD Flags,
_In_ LPTSTR Name,
_In_ DWORD Level,
_Out_ LPBYTE pPrinterEnum,
_In_ DWORD cbBuf,
_Out_ LPDWORD pcbNeeded,
_Out_ LPDWORD pcReturned
);

In Java it's 在Java中

public boolean EnumPrinters(int i, String string, int i1, com.sun.jna.Pointer pntr, int i2,
        com.sun.jna.ptr.IntByReference ibr, com.sun.jna.ptr.IntByReference ibr1);

The problem I am having is that I keep on getting error 122 which means a failure in calling the system call. 我遇到的问题是我不断收到错误122,这意味着调用系统调用失败。 This is my code: 这是我的代码:

IntByReference  pcbNeeded= new  IntByReference();
int pcb=0;
pcbNeeded.setValue(pcb);
IntByReference  pcReturned= new  IntByReference();
int pcR=0;
pcReturned.setValue(pcR);
PRINTER_INFO_4 printer = new PRINTER_INFO_4();  
PRINTER_INFO_4 PRINT[] = (PRINTER_INFO_4[])printer.toArray(20);
Pointer point = PRINT[0].getPointer();
int size = PRINT[0].size();
Winspool.INSTANCE.EnumPrinters(Winspool.PRINTER_ENUM_LOCAL,null, 4, point, size,pcbNeeded ,pcReturned);
System.out.println("Operation started!");
System.out.println(printer.pPrinterName);
int rc =  Kernel32.INSTANCE.GetLastError();
System.out.println("error " + rc);

I just want to get all the installed printer on my computer with the code. 我只想使用代码获取计算机上所有已安装的打印机。

You need to pass the first structure instead of a pointer copy of its address, otherwise JNA doesn't know to automatically sync the Java Structure with native memory. 您需要传递第一个结构而不是其地址的指针副本,否则JNA不会自动将Java结构与本地内存同步。

public boolean EnumPrinters(int i, String string, 
                            int i1, PRINTER_INFO_4 pntr, 
                            int i2, com.sun.jna.ptr.IntByReference ibr,
                            com.sun.jna.ptr.IntByReference ibr1);

You should also preserve the original parameter names, it'll make the mapping much more readable. 您还应该保留原始参数名称,这将使映射更具可读性。

You could also explicitly call Structure.write() on each allocated Structure prior to the native call, and Structure.read() after the call, but JNA does this automatically when it recognizes a Structure in the function signature (including all array elements, if any). 你也可以显式调用Structure.write()上的每个分配Structure之前,本地调用, Structure.read()调用后,但JNA自动执行此操作时,识别Structure的函数签名(包括所有的数组元素,如果有的话)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM