How to read printerStruct.pPrinterName using koffi?
const koffi = require('koffi');
const winspool = koffi.load('winspool.drv');
const kernel32 = koffi.load('kernel32.dll');
const PRINTER_ENUM_LOCAL = 0x00000002;
const PRINTER_ENUM_CONNECTIONS = 0x00000004;
const EnumPrintersW = winspool.func('int __stdcall EnumPrintersW(uint32_t, wchar_t*, uint32_t, void*, uint32_t, uint32_t*, uint32_t*)');
const GetLastError = kernel32.func('uint32_t __stdcall GetLastError()');
const pcbNeeded = Buffer.alloc(4);
const pcReturned = Buffer.alloc(4);
let result = EnumPrintersW(
PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS,
null,
4,
null,
0,
pcbNeeded,
pcReturned
);
let needed = pcbNeeded.readUInt32LE(0);
if (needed === 0) {
const err = GetLastError();
console.error(`Failed to get buffer size. Error: ${err}`);
process.exit(1);
}
const pPrinterEnum = Buffer.alloc(needed);
result = EnumPrintersW(
PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS,
null,
4,
pPrinterEnum,
needed,
pcbNeeded,
pcReturned
);
if (result === 0) {
const err = GetLastError();
console.error(`EnumPrintersW failed. Error: ${err}`);
process.exit(1);
}
needed = pcbNeeded.readUInt32LE(0);
const returned = pcReturned.readUInt32LE(0);
console.log(`Found ${returned} printers:\n`);
const PRINTER_INFO_4 = koffi.struct({
pPrinterName: 'uintptr_t',
pServerName: 'uintptr_t',
Attributes: 'uint32_t',
});
const structSize = koffi.sizeof(PRINTER_INFO_4);
for (let i = 0; i < returned; i++) {
const offset = i * structSize;
const printerStruct = koffi.decode(pPrinterEnum, offset, PRINTER_INFO_4);
console.log(printerStruct);
}
Remy Lebeau
610k36 gold badges516 silver badges875 bronze badges
asked Sep 11, 2025 at 15:21
Volodymyr Bezuglyy
16.9k33 gold badges107 silver badges138 bronze badges
1 Answer 1
Use koffi.decode() to decode any C-style data pointer. You already know how to use it to decode the pPrinterEnum pointer into a struct. Do the same thing with the strings in the struct, eg:
const printerStruct = koffi.decode(pPrinterEnum, offset, PRINTER_INFO_4);
console.log(printerStruct);
const printerName = koffi.decode(printerStruct.pPrinterName, 'wchar_t *');
console.log(printerName);
const serverName = koffi.decode(printerStruct.pServerName, 'wchar_t *');
console.log(serverName);
answered Sep 11, 2025 at 23:30
Remy Lebeau
610k36 gold badges516 silver badges875 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js