Friday, July 28, 2017

Buffer allocation for the P/Invoke tool

Some Windows functions require a buffer to be allocated before calling the function so that a string (or other chunk of data) of variable length can be returned. To make my P/Invoke command-line tool work with these functions, I introduced an instruction to create a slot of a pointer-typed kind, allocate a buffer of a given length, and fill the slot with the pointer to the buffer. Slots can be allocated with variable size, i.e. with a length provided by an existing slot's data. The length of a slot's buffer can be passed in a call using another new instruction. Since some functions actually care about character length rather than raw byte length, a unit - "bytes" or "chars" can be supplied.

This command (broken across lines for readability) takes advantage of these features to get the computer's name.

newslot int size = 0;
call kernel32.dll!GetComputerNameW (nullptr, slotptr size); 
allocslot lpwstr name: size chars;
call kernel32.dll!GetComputerNameW (slotdata name, slotptr size);
readslot name

No comments:

Post a Comment