简体   繁体   中英

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. I want to access the EnumPrinters() function, and here are the parameters to it:

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

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. 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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