Memory Reference
Reference for the object created with api.Memory(), which handles native memory (structures and buffers).
- It is an object for reading and writing, from JavaScript, structures passed to the Win32 API (such as
RECT,POINT, andLOGFONT) and buffers exchanged by pointer. - Related: te Reference, api Reference (
api.Memoryand others), FolderItems Reference
Notation: P = property, M = method. Member names and field names are matched case-insensitively (
rc.leftandrc.Leftare the same). In actual scripts, however, the spelling used in the structure definition (rc.left,pt.x,mii.fMask, and so on) is used.
Table of Contents
- How to Obtain
- Common Members
- Read / Write and VT Constants
- Structure Fields
- Primitive-Type Memory
- Notes
- Examples
1. How to Obtain
api.Memory(type [, count [, ptr]])
| Call | Description |
|---|---|
api.Memory("RECT") |
Creates memory of the size of the named structure (zero-initialized) |
api.Memory("WCHAR", 260) |
Creates memory by specifying the element type and the count (for WCHAR, a buffer of 260 characters) |
api.Memory("WCHAR", "string") |
Creates a WCHAR buffer that holds a copy of the string with a terminating NUL |
api.Memory(size) |
If you pass a number, creates a buffer of that many bytes (no type name) |
api.Memory(size, count) |
Creates a buffer of size * count bytes |
api.Memory(size, count, ptr) |
Does not allocate; refers directly to the memory that the existing pointer ptr points to (size * count bytes; it does not take ownership) |
api.Memory(SafeArray) |
Creates it by copying the contents of a SafeArray (such as VT_UI1 \| VT_ARRAY) |
api.Memory(IStream, size) |
Creates it by reading up to size bytes from the start of the stream |
- If creation fails (for example, an unknown type name with no number specified), empty (
undefined) is returned. - For structures whose first member is a
cbSize-type field, the structure size is set automatically in the first 4 bytes at creation time (those marked ✓ in the "Auto cbSize" column of Chapter 4). - Structure names are matched case-insensitively. For the type names you can use, see Chapter 4 and Chapter 5.
2. Common Members
| Name | Kind | Description |
|---|---|---|
P |
P (read-only) | The start address of the memory (a pointer value). Used when passing a pointer, as in api.xxx(…, mem.P) |
Size |
P (read-only) | The total number of bytes |
Count / length |
P (read-only) | The number of elements |
Item(i [, value]) |
M | Reads the i-th element (0-based). If a second argument is passed, it writes (when the element is 1/2/4/8 bytes). mem[i] does the same |
_NewEnum |
P | For enumeration (for...in / Enumerator) |
Read(offset, vt [, len]) |
M | Reads a value of type vt from offset (in bytes) (Chapter 3) |
Write(offset, vt, value [, len]) |
M | Writes a value of type vt at offset (in bytes) |
Clone() |
M | Returns a new Memory with a copy of the contents (empty if the size is 0) |
Free() |
M | Releases the allocated memory and the held strings. The object can no longer be used afterwards (P is 0) |
_BLOB |
P | Reads and writes the allocated buffer as a binary string (BSTR). If the size changes on assignment, the buffer is reallocated. It returns nothing for a Memory that refers to an external pointer |
Behavior of Item
- When the element size (
Size / Count) is 1, 2, or 4 bytes: returns an integer (signed; note thatBYTEis also read as signed, likechar). - 8 bytes: returns a 64-bit integer (
int64) except forPOINT. ForPOINT, it returns a Memory (a view of the element below). - Otherwise: returns a Memory that points to that element (a view of the same memory; not a copy). This can be used for arrays of structures.
- Writing is valid only when the element size is 1 to 8 bytes. When you write a string to a
BSTR/LPWSTRtype, the Memory holds an internal copy and stores its pointer.
3. Read / Write and VT Constants
For vt in Read(offset, vt [, len]) / Write(offset, vt, value [, len]), use the VT_* constants of consts.js or the numbers in the table below.
| vt | Value | Return value of Read | Input of Write |
|---|---|---|---|
VT_BOOL |
11 | bool | number |
VT_I1 / VT_UI1 |
16 / 17 | integer (1 byte) | integer |
VT_I2 / VT_UI2 |
2 / 18 | integer (2 bytes) | integer |
VT_I4 / VT_UI4 |
3 / 19 | integer (4 bytes) | integer |
VT_I8 / VT_UI8 |
20 / 21 | 64-bit integer | 64-bit integer |
VT_R4 / VT_R8 |
4 / 5 | floating point | (writing is not supported) |
VT_PTR / VT_BSTR |
26 / 8 | pointer value (pointer width) | pointer value |
VT_LPWSTR |
31 | string (NUL-terminated). If len is specified, the first len characters |
string (copied including the NUL; truncated so as not to exceed the buffer) |
VT_LPSTR |
30 | ANSI string | ANSI string |
VT_USERDEFINED / VT_UTF8 |
29 | UTF-8 string | UTF-8 string |
VT_FILETIME |
64 | UNIX time (ms, a number) | date / date-time |
VT_CY |
6 | {x, y} (a value that can be treated as a POINT) |
POINT / {x,y} |
VT_CARRAY |
28 | RECT (copied into a new Memory) | RECT (Memory) |
VT_CLSID |
72 | GUID string ({xxxxxxxx-…}) |
GUID string |
VT_VARIANT |
12 | VARIANT | VARIANT |
vt \| VT_ARRAY (0x2000) |
- | SafeArray (element type vt, len elements; all the rest if omitted) |
SafeArray (len elements) |
- The constants defined in
consts.jsareVT_EMPTYVT_NULLVT_I1VT_I2VT_I4VT_I8VT_UI1VT_UI2VT_UI4VT_UI8VT_R4VT_R8VT_BSTRVT_UTF8VT_LPSTRVT_LPWSTRVT_PTRVT_VARIANTVT_RECORDVT_USERDEFINEDVT_ARRAY.VT_BOOLVT_FILETIMEVT_CYVT_CARRAYVT_CLSIDare not defined, so specify them by number (11 / 64 / 6 / 28 / 72). offsetis the number of bytes from the start. No range checking is performed, so make sure not to exceed the size of the buffer.- If you specify an unsupported
vttoRead, empty is returned. WithWrite, nothing happens.
4. Structure Fields
A Memory created with a structure name can be read and written through properties named after the fields (for example rc.left, pt.x = 10). Field names are exactly the names in the structure definition, and are not case-sensitive.
How to read the types: no mark = int (a 4-byte integer), (ptr) = a pointer value, (string) = reading and writing a fixed-length string (a WCHAR array) inside the structure, (string*) = a string pointer (when assigned, the Memory holds a copy of the string and stores its pointer), (RECT) / (POINT) = returns the structure as a value (RECT is a copy in a new Memory, POINT is {x,y}), (WORD) = 2 bytes, (BYTE) = 1 byte, (bool) = BOOL.
| Structure | Auto cbSize | Fields |
|---|---|---|
BITMAP |
bmBits(ptr), bmBitsPixel(WORD), bmHeight, bmPlanes(WORD), bmType, bmWidth, bmWidthBytes |
|
CHOOSECOLOR |
✓ | Flags, hInstance(ptr), hwndOwner(ptr), lCustData(ptr), lpCustColors(ptr), lpfnHook(ptr), lpTemplateName(string*), lStructSize, rgbResult |
CHOOSEFONT |
✓ | ___MISSING_ALIGNMENT__(WORD), Flags, hDC(ptr), hInstance(ptr), hwndOwner(ptr), iPointSize, lCustData(ptr), lpfnHook(ptr), lpLogFont(ptr), lpszStyle(string), lpTemplateName(string), lStructSize, nFontType(WORD), nSizeMax, nSizeMin, rgbColors |
COPYDATASTRUCT |
cbData, dwData(ptr), lpData(ptr) |
|
DIBSECTION |
dsBitfields0, dsBitfields1, dsBitfields2, dsBm(ptr), dsBmih(ptr), dshSection(ptr), dsOffset |
|
DRAWITEMSTRUCT |
CtlID, CtlType, hDC(ptr), hwndItem(ptr), itemAction, itemData(ptr), itemID, itemState, rcItem(RECT) |
|
EXCEPINFO |
bstrDescription(string), bstrHelpFile(string), bstrSource(string*), dwHelpContext, pfnDeferredFillIn(ptr), pvReserved(ptr), scode, wCode(WORD), wReserved(WORD) |
|
FINDREPLACE |
✓ | Flags, hInstance(ptr), hwndOwner(ptr), lCustData(ptr), lpfnHook(ptr), lpstrFindWhat(string), lpstrReplaceWith(string), lpTemplateName(string*), lStructSize, wFindWhatLen(WORD), wReplaceWithLen(WORD) |
FOLDERSETTINGS |
fFlags, ImageSize, Options, ViewFlags, ViewMode |
|
GUITHREADINFO |
✓ | cbSize, flags, hwndActive(ptr), hwndCapture(ptr), hwndCaret(ptr), hwndFocus(ptr), hwndMenuOwner(ptr), hwndMoveSize(ptr), rcCaret(RECT) |
HDITEM |
cchTextMax, cxy, fmt, hbm(ptr), iImage, iOrder, lParam, mask, pszText(string*), pvFilter(ptr), state, type |
|
ICONINFO |
fIcon(bool), hbmColor(ptr), hbmMask(ptr), xHotspot, yHotspot |
|
ICONMETRICS |
iHorzSpacing, iTitleWrap, iVertSpacing, lfFont(ptr) |
|
KEYBDINPUT |
dwExtraInfo(ptr), dwFlags, time, type, wScan, wVk |
|
LOGFONT |
lfCharSet(BYTE), lfClipPrecision(BYTE), lfEscapement, lfFaceName(string), lfHeight, lfItalic(BYTE), lfOrientation, lfOutPrecision(BYTE), lfPitchAndFamily(BYTE), lfQuality(BYTE), lfStrikeOut(BYTE), lfUnderline(BYTE), lfWeight, lfWidth |
|
LVBKIMAGE |
cchImageMax, hbm(ptr), pszImage(string*), ulFlags, xOffsetPercent, yOffsetPercent |
|
LVCOLUMN |
cchTextMax, cx, cxDefault, cxIdeal, cxMin, fmt, iImage, iOrder, iSubItem, mask, pszText(string*) |
|
LVFINDINFO |
flags, lParam, psz(string*), pt(POINT), vkDirection |
|
LVGROUP |
✓ | cbSize, cchDescriptionBottom, cchDescriptionTop, cchFooter, cchHeader, cchSubsetTitle, cchSubtitle, cchTask, cItems, iExtendedImage, iFirstItem, iGroupId, iTitleImage, mask, pszDescriptionBottom(string), pszDescriptionTop(string), pszFooter(string), pszHeader(string), pszSubsetTitle(string), pszSubtitle(string), pszTask(string*), state, stateMask, uAlign |
LVHITTESTINFO |
flags, iGroup, iItem, iSubItem, pt(POINT) |
|
LVITEM |
cchTextMax, cColumns, iGroup, iGroupId, iImage, iIndent, iItem, iSubItem, lParam, mask, piColFmt(ptr), pszText(string*), puColumns(ptr), state, stateMask |
|
MEASUREITEMSTRUCT |
CtlID, CtlType, itemData(ptr), itemHeight, itemID, itemWidth |
|
MENUINFO |
✓ | cbSize, cyMax, dwContextHelpID, dwMenuData(ptr), dwStyle, fMask, hbrBack(ptr) |
MENUITEMINFO |
✓ | cbSize, cch, dwItemData(ptr), dwTypeData(string*), fMask, fState, fType, hbmpChecked(ptr), hbmpItem(ptr), hbmpUnchecked(ptr), hSubMenu(ptr), wID |
MONITORINFOEX |
✓ | cbSize, dwFlags, rcMonitor(RECT), rcWork(RECT), szDevice(string) |
MOUSEINPUT |
dwExtraInfo(ptr), dwFlags, dx, dy, mouseData, time, type |
|
MSG |
hwnd(ptr), lParam(ptr), message, pt(POINT), time, wParam(ptr) |
|
NMCUSTOMDRAW |
dwDrawStage, dwItemSpec(ptr), hdc(ptr), hdr(ptr), lItemlParam(ptr), rc(RECT), uItemState |
|
NMHDR |
code, hwndFrom(ptr), idFrom |
|
NMLVCUSTOMDRAW |
clrFace, clrText, clrTextBk, dwItemType, iIconEffect, iIconPhase, iPartId, iStateId, iSubItem, nmcd(ptr), rcText(RECT), uAlign |
|
NMTVCUSTOMDRAW |
clrText, clrTextBk, iLevel, nmcd(ptr) |
|
NONCLIENTMETRICS |
✓ | cbSize, iBorderWidth, iCaptionHeight, iCaptionWidth, iMenuHeight, iMenuWidth, iPaddedBorderWidth, iScrollHeight, iScrollWidth, iSmCaptionHeight, iSmCaptionWidth, lfCaptionFont(ptr), lfMenuFont(ptr), lfMessageFont(ptr), lfSmCaptionFont(ptr), lfStatusFont(ptr) |
NOTIFYICONDATA |
✓ | cbSize, dwInfoFlags, dwState, dwStateMask, guidItem(ptr), hBalloonIcon(ptr), hIcon(ptr), hWnd(ptr), szInfo(string), szInfoTitle(string), szTip(string), uCallbackMessage, uFlags, uID, uTimeout, uVersion |
OSVERSIONINFO |
✓ | dwBuildNumber, dwMajorVersion, dwMinorVersion, dwOSVersionInfoSize, dwPlatformId, szCSDVersion(string), wProductType(BYTE), wReserved(BYTE), wServicePackMajor(WORD), wServicePackMinor(WORD), wSuiteMask(WORD) |
OSVERSIONINFOEX |
✓ | dwBuildNumber, dwMajorVersion, dwMinorVersion, dwOSVersionInfoSize, dwPlatformId, szCSDVersion(string), wProductType(BYTE), wReserved(BYTE), wServicePackMajor(WORD), wServicePackMinor(WORD), wSuiteMask(WORD) |
PAINTSTRUCT |
fErase(bool), fIncUpdate(bool), fRestore(bool), hdc(ptr), rcPaint(RECT), rgbReserved(BYTE) |
|
POINT |
x, y |
|
RECT |
bottom, left, right, top |
|
SECURITY_ATTRIBUTES |
bInheritHandle(bool), lpSecurityDescriptor(ptr), nLength |
|
SHELLEXECUTEINFO |
✓ | cbSize, dwHotKey, fMask, hIcon(ptr), hInstApp(ptr), hkeyClass(ptr), hMonitor(ptr), hProcess(ptr), hwnd(ptr), lpClass(string), lpDirectory(string), lpFile(string), lpIDList(ptr), lpParameters(string), lpVerb(string*), nShow |
SHFILEINFO |
dwAttributes, hIcon(ptr), iIcon, szDisplayName(string), szTypeName(string) |
|
SHFILEOPSTRUCT |
fAnyOperationsAborted(bool), fFlags(WORD), hNameMappings(ptr), hwnd(ptr), lpszProgressTitle(string), pFrom(string), pTo(string*), wFunc |
|
SIZE |
cx, cy |
|
TCHITTESTINFO |
flags, pt(POINT) |
|
TCITEM |
cchTextMax, dwState, dwStateMask, iImage, lParam(ptr), mask, pszText(string*) |
|
TOOLINFO |
✓ | cbSize, hinst(ptr), hwnd(ptr), lParam(ptr), lpReserved(ptr), lpszText(string*), rect(RECT), uFlags, uId(ptr) |
TVHITTESTINFO |
flags, hItem(ptr), pt(POINT) |
|
TVITEM |
cChildren, cchTextMax, hItem(ptr), iImage, iSelectedImage, lParam(ptr), mask, pszText(string*), state, stateMask |
|
WIN32_FIND_DATA |
cAlternateFileName(string), cFileName(string), dwFileAttributes, dwReserved0, dwReserved1, ftCreationTime(FILETIME), ftLastAccessTime(FILETIME), ftLastWriteTime(FILETIME), nFileSizeHigh, nFileSizeLow |
Fixed-length string fields such as
LOGFONT.lfFaceName,SHFILEINFO.szDisplayName,WIN32_FIND_DATA.cFileName, andNOTIFYICONDATA.szTipare read and written as strings.ftCreationTime/ftLastAccessTime/ftLastWriteTimeofWIN32_FIND_DATAcan be read as UNIX time (ms).CHOOSEFONTalso exposes an internal reserved field for alignment (___MISSING_ALIGNMENT__), but you normally do not use it. Only the first byte ofPAINTSTRUCT.rgbReservedis referenced.
5. Primitive-Type Memory
Type names that are not structures can also be specified to api.Memory(). To read and write element by element, use Item(i) / mem[i].
| Type name | Element size | Notes |
|---|---|---|
BYTE / char |
1 | BYTE can read and write the first element through the type-name property (mem.BYTE) |
WORD / WCHAR |
2 | WCHAR is used as a string buffer, and Read(0, VT_LPWSTR) turns it into a string |
DWORD / int |
4 | The first element can be read and written with mem.DWORD / mem.int |
HANDLE / LPWSTR / BSTR |
pointer width | The first element can be read and written with mem.HANDLE / mem.LPWSTR |
GUID |
16 | Read the GUID string with Read(0, VT_CLSID) |
KEYSTATE |
256 | 256 bytes for GetKeyboardState / SetKeyboardState |
VARIANT |
size of VARIANT | Put values in and take them out with Read(0, VT_VARIANT) / Write(…, VT_VARIANT, v) |
6. Notes
- When you assign a string to a string pointer (
BSTR/LPWSTRtype), the Memory holds an internal copy. It stays valid until youFree()the Memory or it is discarded. While you are passing it to an API, keep the Memory in a variable. Memory(size, count, ptr)only refers to existing memory and does not own it. Do not access it after the original memory has been freed.- After
Free(), the Memory'sPis 0 and it cannot be read or written. - To create an array of structures, specify the element count as in
api.Memory("POINT", n)and use it asmem[i].x(the elements are views of the same memory).
7. Examples
// Get a RECT
const rc = api.Memory("RECT");
api.GetWindowRect(te.hwnd, rc);
const w = rc.right - rc.left;
const h = rc.bottom - rc.top;
// POINT
const pt = api.Memory("POINT");
api.GetCursorPos(pt);
const x = pt.x, y = pt.y;
// String buffer (WCHAR)
const s = api.Memory("WCHAR", "Hello");
const text = s.Read(0, VT_LPWSTR); // "Hello"
s.Write(0, VT_LPWSTR, "World"); // overwrite within the buffer
// Set structure fields (cbSize is set automatically)
const mii = api.Memory("MENUITEMINFO");
mii.fMask = MIIM_STRING | MIIM_ID;
mii.wID = 1;
mii.dwTypeData = "Item"; // the Memory holds the string
api.InsertMenuItem(hMenu, 0, true, mii);
// Conversion to and from a binary string (BSTR)
const mem = api.Memory(4);
mem.Write(0, VT_I4, 0x12345678);
const n = mem.Read(0, VT_I4); // 0x12345678
const bytes = mem.Read(0, VT_UI1 | VT_ARRAY); // SafeArray (4 bytes)
// Date (FILETIME)
const fd = api.Memory("WIN32_FIND_DATA");
const hFind = api.FindFirstFile("C:\\Windows\\notepad.exe", fd);
const modified = new Date(fd.ftLastWriteTime); // UNIX time (ms)
// Clone and free
const copy = rc.Clone();
copy.Free();