Win32 assembly: 12. Memory management and file input output

zhaozj2021-02-17  60

Class 12 memory management and file input / output

In this lesson, we will learn the basic memory management and file input / output operations. In addition, we will also use the common dialog of the class as our display "equipment".

theory:

From the user's point of view, Win32's memory management is very simple and clear. Each application has its own independent 4G address space. This memory mode is called "flat" address mode, all segment registers or descriptors point to the same start address, all address offset is 32-bit Length, such an application is not required to change the selector to access your own up to 4G address space. This memory management mode is very simple and easy to manage, and we don't have to deal with those who are annoying "NEAR" and "FAR" pointers. There are two main types of APIs under W16: global and partial. "Global" API allocation is in other segments, which looks from a memory perspective. They are some "far" function or remote process calls, "local" API, just deal with the plot of the process, so put them " Near "(near) function or proximity process call. In WIN32, these two memory patterns are the same, no matter whether you call GlobalAlloc or Localalloc, the result is the same. As for the process of distributing and using memory:

Call the GLOBALALLOC function Assign a single memory, which returns the assigned memory handle. Call the GLOBALLOCK function to lock the memory block, which accepts a memory handle as a parameter, and then returns a pointer to the locked memory block. You can use this pointer to read and write memory. Call the GlobalUnLock function to unlock the previously locked memory, which makes the pointer to the memory block invalid. Call the GLOBALFREE function to release the memory block. You must pass the function a memory handle.

In Win32, you can also use the "Local" replacement memory allocation API function with "global" in the "Global" word, which is also Localalloc, Locallock, etc. Use the GMEM_FIXED flag using the GMEM_FIXED flag when the function GlobalLall can be used. After using this flag, Global / Localaloc returns to the pointer to the assigned memory instead of the handle, so you don't have to call Global / Locallock to lock the memory, just call the Global / LocalFree directly. However, in this lesson, we only use traditional methods because there are many source code to be written in this way.

Win32's file input / output API and DOS look at almost the same (Translator Note: Maybe no matter how different internal implementation can be imagined to expose to the interface of all file systems to the application writer, the function should be basically the same), Different only to process file input / output under DOS into the call to the API function. The following is the basic steps:

Call the CreateFile function Generate a file that can be applied to many aspects, in addition to disk files, we can also use to open communication ports, pipes, drivers, or consists. If successful, you will return the handle of the file or device. You can then use this handle to complete the file or device operation. Call SetFilePointer to move the file pointer to where you want to read. Then call ReadFile or Writefile to complete the actual read and write. These functions will handle data transfer between files and memory, so you can remove yourself to allocate complicated trivial matters. Call the CloseHandle to close the file. This function accepts a previously opened file handle.

content:

The following code segment demonstrates: Open a "Open File" dialog box, the user can choose to open a text file, then open the content of the text file in an edit control, and the user can edit the text file and select Save .

.386 .model flat, stdcall option casemap: none WinMain proto: DWORD,: DWORD,: DWORD,: DWORD include /masm32/include/windows.inc include /masm32/include/user32.inc include / masm32 / include / kernel32. inc include /masm32/include/comdlg32.inc includelib /masm32/lib/user32.lib includelib /masm32/lib/kernel32.lib includelib /masm32/lib/comdlg32.lib.const IDM_OPEN equ 1 IDM_SAVE equ 2 IDM_EXIT equ 3 MAXSIZE equ 260 Memsize EQU 65535

Editid EQU 1; ID of the Edit Control

.data classname DB "Win32asmeditclass", 0 AppName DB "Win32 ASM Edit", 0 EditClass DB "Edit", 0 Menuname DB "Firstmenu", 0 OFN OpenFileName <> Filterstring DB "All Files", 0, "*. *" 0 DB "text files", 0, "*. Txt", 0,0 buffer db maxsize dup (0)

? .Data hInstance HINSTANCE CommandLine LPSTR hwndEdit HWND;??? Handle to the edit control hFile HANDLE;? File handle hMemory HANDLE;? Handle to the allocated memory block pMemory DWORD;? Pointer to the allocated memory block SizeReadWrite DWORD;? Number of Bytes Actually Read or Write

. Code Start: Invoke GetModuleHandle, Null Mov Hinstance, Eax Invoke Getcommandline Mov Commandline, Eax Invoke Winmain, Hinstance, Null, CommandLine, SW_SHOWDEFAULT INVOKE EXITPROCESS, EAX

WinMain proc hInst: HINSTANCE, hPrevInst: HINSTANCE, CmdLine: LPSTR, CmdShow: SDWORD LOCAL wc: WNDCLASSEX LOCAL msg: MSG LOCAL hwnd: HWND mov wc.cbSize, SIZEOF WNDCLASSEX mov wc.style, CS_HREDRAW or CS_VREDRAW mov wc.lpfnWndProc, OFFSET WndProc mov wc.cbClsExtra, NULL mov wc.cbWndExtra, NULL push hInst pop wc.hInstance mov wc.hbrBackground, COLOR_WINDOW 1 mov wc.lpszMenuName, OFFSET MenuName mov wc.lpszClassName, OFFSET ClassName invoke LoadIcon, NULL, IDI_APPLICATION mov wc. hIcon, eax mov wc.hIconSm, eax invoke LoadCursor, NULL, IDC_ARROW mov wc.hCursor, eax invoke RegisterClassEx, addr wc invoke CreateWindowEx, WS_EX_CLIENTEDGE, aDDR ClassName, aDDR AppName, / WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, / CW_USEDEFAULT, 300,200, NULL, NULL , / Hinst, Null Mov HWnd, Eax Invoke Showwindow, HWnd, SW_SHOWNORMAL INVOKE UPDATEWINDOW, HWND .WHILE TRUE INVOKE GETMESSAGE, ADD R msg, null, 0 ,0 .break .if (! EAX) Invoke TranslateMessage, Addr Msg Invoke DispatchMessage, Addr Msg .Endw Mov Eax, Msg.wParam Ret Winmain Endp

WndProc proc uses ebx hWnd: HWND, uMsg: UINT, wParam: WPARAM, lParam: LPARAM .IF uMsg == WM_CREATE invoke CreateWindowEx, NULL, ADDR EditClass, NULL, / WS_VISIBLE or WS_CHILD or ES_LEFT or ES_MULTILINE or / ES_AUTOHSCROLL or ES_AUTOVSCROLL, 0 , / 0,0,0, hwnd, editid, / hinstance, null mov hwndedit, eax invoke setfocus, hwndit; ========================= =====================; Initialize the Members of OpenFileName Structure; ===================== ================================== Mov off.lstructSize, Sizeof offn Push HWnd pop offs.hwndowner push hinstance pop offshinstance mov offslpstrfilter, offset FilterString mov ofn.lpstrFile, OFFSET buffer mov ofn.nMaxFile, MAXSIZE .ELSEIF uMsg == WM_SIZE mov eax, lParam mov edx, eax shr edx, 16 and eax, 0ffffh invoke MoveWindow, hwndEdit, 0,0, eax, edx, TRUE .Lse IF umsg == wm_destroy invoke postquitmessage, null .elseif umsg == wm_command mov Eax, wparam .IF lparam == 0 .IF AX ==

IDM_OPEN mov ofn.Flags, OFN_FILEMUSTEXIST or / OFN_PATHMUSTEXIST or OFN_LONGNAMES or / OFN_EXPLORER or OFN_HIDEREADONLY invoke GetOpenFileName, ADDR ofn .if eax == TRUE invoke CreateFile, ADDR buffer, / GENERIC_READ or GENERIC_WRITE, / FILE_SHARE_READ or FILE_SHARE_WRITE, / NULL, OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE , / NULL mov hFile, eax invoke GlobalAlloc, GMEM_MOVEABLE or GMEM_ZEROINIT, MEMSIZE mov hMemory, eax invoke GlobalLock, hMemory mov pMemory, eax invoke ReadFile, hFile, pMemory, MEMSIZE-1, ADDR SizeReadWrite, NULL invoke SendMessage, hwndEdit, WM_SETTEXT, NULL , Pmemory Invoke Closeh andle, hFile invoke GlobalUnlock, pMemory invoke GlobalFree, hMemory .endif invoke SetFocus, hwndEdit .elseif ax == IDM_SAVE mov ofn.Flags, OFN_LONGNAMES or / OFN_EXPLORER or OFN_HIDEREADONLY invoke GetSaveFileName, ADDR ofn .if eax ==

TRUE invoke CreateFile, ADDR buffer, / GENERIC_READ or GENERIC_WRITE, / FILE_SHARE_READ or FILE_SHARE_WRITE, / NULL, CREATE_NEW, FILE_ATTRIBUTE_ARCHIVE, / NULL mov hFile, eax invoke GlobalAlloc, GMEM_MOVEABLE or GMEM_ZEROINIT, MEMSIZE mov hMemory, eax invoke GlobalLock, hMemory mov pMemory, eax invoke SendMessage, hwndEdit, WM_GETTEXT, MEMSIZE-1, pMemory invoke WriteFile, hFile, pMemory, eax, ADDR SizeReadWrite, NULL invoke CloseHandle, hFile invoke GlobalUnlock, pMemory invoke GlobalFree, hMemory .endif invoke SetFocus, HWndIt .ELSE Invoke DestroyWindow, Hwnd .ndif. Nex, Hwnd, Umsg, WParam, LParam Ret, WPARAM, LPARAM RETPROC END START analysis:

Invoke CreateWindowex, NULL, AddR Editclass, Null, /

WS_VISible or WS_CHILD or ES_LEFT or ES_MULTILINE OR /

ES_AUTOHSCROLL OR ES_AUTOVSCROLL, 0, /

0,0,0, hwnd, editid, /

Hinstance, NULL

Mov hwndedit, EAX

When processed WM_CREATE messages, we create an editing control. Note that we set the relevant parameters of the control size to 0, because we will reset the size of the editing control later so that it covers the entire client area of ​​the parent window. Note: In this example, we don't have to call ShowWindow to display the editing control, because the WS_Visible flag is set in its style when creating, you can also use this tip when you create a parent window.

; ============================================================; Initialize Thae MEMBERS OF OpenFileName Structure; ============================================= = mov ofn.lStructSize, SIZEOF ofn push hWnd pop ofn.hWndOwner push hInstance pop ofn.hInstance mov ofn.lpstrFilter, OFFSET FilterString mov ofn.lpstrFile, OFFSET buffer mov ofn.nMaxFile, MAXSIZE create an edit control after the finish, we initial words ofn Member of the variable. This structural variable is used later in saving the file later, therefore only initializes the common part to be used. The processing part of the WM_CREATE message is the excellent place to perform this initialization.

.ELSEIF UMSG == WM_SIZE MOV EAX, LPARAM MOV EDX, EAX SHR EDX, 16 And Eax, 0fffh Invoke MoveWindow, Hwndit, 0, 0, Eax, EDX, TRUE

When the client part of the main window changes, our application will receive the WM_SIZE message. Of course, the window will also receive the message for the first time. To receive the message, the main window must have a CS_VREDRAW and a CS_HREDRAW style. We should put the action of the zoom editing control. We have to turn the editorial control as large as our window client area, so we must get the size of the parent window client area. These values ​​are included in the parameter LPARAM, and the high character part of LParam is the high customer area, the bottom part is the width of the client area. Then we call the MoveWindow function to re-adjust the size of the edit control, which can not only move the location of the window, but also change the size of the window.

. =m = = = g g g g g n n n n

When the user selects the File / Open menu item, we populate other members of the OFN, and then call the GetopenFileName function to display an "Open File" dialog.

.if eax == TRUE invoke CreateFile, ADDR buffer, / GENERIC_READ or GENERIC_WRITE, / FILE_SHARE_READ or FILE_SHARE_WRITE, / NULL, OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, / NULL mov hFile, eax if the user selects a file, we call CreateFile function to open. We set the flag bit to let the file files can read and write. After the file is opened, we save the returned file handle in a global variable for later use. The CreateFile function is very wide, its prototype is as follows:

CreateFile proto lpFileName: DWORD, / dwDesiredAccess: DWORD, / dwShareMode: DWORD, / lpSecurityAttributes: DWORD, / dwCreationDistribution: DWORD /, dwFlagsAndAttributes: DWORD /, hTemplateFile: DWORD

DwdesiredAccess specifies the operation you want.

0 Open the file to query its properties. Generic_read opens the file reads generic_write Opens the file.

DWSHAREMODE Specifies the sharing mode of the file.

0 Do not allow other processes to share, that is, when you open the file, other processes will fail when you open the file. FILE_SHARE_READ allows other processes to read. FILE_SHARE_WRITE allows other processes to write.

LPSecurityAttributes This property is invalid under Win95. DWCREATIONDISTRIBUTION specifies the action that you want to generate in its existence and not presented.

CREATE_NEW Generates a new file. If the file already exists, it fails. CREATE_ALWAYS generates a new file regardless of whether the file is present. Open_existing opens the existing file. If the file does not exist, it fails. Open_ALWAYS opens the file, if the file does not exist, it is generated, which is the same as the CREATE_NEW flag in DWCREATIONDistribution. Truncate_existing Opens the file. When the file is opened, the length of the file is reduced to zero (i.e., not the original file completely). This requires the calling process to have the right of generic_write. If the specified file does not exist, the function returns a failure.

DWFlagsandAttributes Specifies the properties of the file.

FILE_ATTRIBUTE_ARCHIVE This file has the properties of the general archive file. Users can use this flag to mark the deletion and backup of the file. File_attribute_compressed file or directory is compressed. For files, all data is compressed, and the newly generated subdirectories and files are compressed for the directory. FILE_ATTRIBUTE_NORMAL This file does not have a general property set. This logo can only be used separately. FILE_ATTRIBUTE_HIDEN This file is a hidden file that will not be displayed when browsing a general file directory. FILE_ATTRIBUTE_READOONLY This file is a read-only file. The application can read it, but it cannot be written. File_attribute_system This file is a system file. INVOKE GLOBALLOC, GMEM_MOVEABLE OR GMEM_ZEROINIT, MEMSIZE

Mov HMemory, EAX

Invoke GlobalLock, HMemory

Mov Pmemory, EAX

After the file is opened, we will assign a memory for subsequent API functions ReadFile and WriteFile. We use the flag GMEM_MOVEABLE to make Windows always move the memory block to a reliable memory, GMEM_ZEROINIT tells Windows to zero the just allocated memory. If the globalalloc call is successful, return the handle of the memory block in EAX, and we pass the handle to the GLOBALLOCK function to get a pointer to the memory block.

Invoke Readfile, Hfile, Pmemory, Memsize-1, Addr SizeReadwrite, Null Invoke SendMessage, Hwndit, WM_SETTEXT, NULL, PMEMORY

After the memory block is available, we call the ReadFile function from reading data from the file. For the first open file, the file's pointer is placed at the offset 0, and we read from the offset 0 in this case. The first parameter of the readFile is the file handle. The second parameter is a pointer to the memory block. The next parameter is the length of the data to read, the fourth parameter is a pointer to the DWORD type parameter, which is used The length of the actual read data is stored. After reading it, we store these contents into the editor control, which is done with messaging, and we pass the message WM_SETTEXT to the edit control, where the parameter LPARAM contains a pointer to the memory block. Here, the editing control can display the contents of the file in its client area.

Invoke Closehandle, Hfile Invoke Globalunlock, Pmemory Invoke Globalfree, HMemory .ndif

We no longer need to let the file open, because our purpose is to save the modified data to another instead of the previous file. So we can call CloseHandle to close the file. Next we unlock the memory block and release it. In fact, we can do not release the memory blocks, and reuse in future operations. In order to demonstrate the original origin, we chose to release it.

Invoke setfocus, hwndedit

When the open file dialog is displayed on the screen, the input focus is switched to the dialog. So after the dialog is turned off, we must switch the focus to the editing control. Now open the stage of the file, the user can edit the files they open. When the user wants to save the modified content to the disk, you must select the File / Save menu item, and a saved file dialog is displayed. The Save Save File dialog is actually the same as that open the open file dialog. You can even think that they are just the same name. Here you can multiplex the values ​​of the previously set members of most OFN variables.

Mov off.flags, OFN_LONGNAMES OR / OFN_EXPLORER OR OFN_HIDEREADONLY

In this example we will generate a new file, so it must not have an off -_filemustexist and OFN_PATHMUSTEXIST flag. The DWCreationDistribution parameter should have a CREATE_NEW flag. The next code and open question dialog are basically the same. Final call:

Invoke SendMessage, HWndedit, WM_Gettext, Memsize-1, Pmemory Invoke Writefile, Hfile, Pmemory, Eax, Addr SizeReadwrite, NULL

Now let's write the modified data back from the editing control, and then write new files from the memory block.

转载请注明原文地址:https://www.9cbs.com/read-30126.html

New Post(0)