Tutorials to .com

Tutorials to .com » Software » Asm » WIN32 compilation: 12. Memory management and file input and output

WIN32 compilation: 12. Memory management and file input and output

Print View , by: iSee ,Total views: 16 ,Word Count: 3746 ,Date: Fri, 8 May 2009 Time: 10:36 AM

12th class memory management and file input / output


This lesson we will learn the basic memory management and file input / output operations knowledge. In addition, we will also learn to use the common dialog classes as part of our show "equipment."

Theory:

From the user's point of view, WIN32 memory management is very simple and straightforward. Each application has its own independent of the 4G address space, this memory model is called "flat" type the address mode register or all of the above descriptors are the starting point to the same address, all addresses are 32-bit offset length, no need for such a transformation application selectors can access their own address space of up to 4G. This memory management model is very simple and manageable, and we no longer need and those annoying "near" and "far" pointer of the deal.
In W16, there are two main types of the API: global and local. "Global" distribution of the API of the paragraph in the other, so that the point of view from memory they are "far" (far) function call or procedure call away, "local" API as long as the reactor and the process of dealing with, so they called the " near "(Near) function or the last procedure call. In WIN32, this two types of memory model is the same, whether you call GlobalAlloc or LocalAlloc, the results are the same.
The allocation and use of memory is the same process:

  1. GlobalAlloc call a memory allocation function, the function will return to handle memory allocation.
  2. GlobalLock call memory block lock function, the function to accept a memory handle as a parameter, and then return to a point to lock the memory block pointer.
  3. You can use the guidelines to read and write memory.
  4. GlobalUnlock function call to unlock the previously locked memory, the function of making the pointer point to invalid memory block.
  5. GlobalFree call function to release memory blocks. You must be a memory to handle this function.

In WIN32, you can also use "Local" to replace memory allocation API function with the "Global" function word "Global", also used LocalAlloc, LocalLock and so on.
Call function in the use of GlobalAlloc flag GMEM_FIXED can further simplify the operation. After the use of the logo, Global / LocalAlloc return to the point of the pointer has been allocated memory rather than the handle, so do not call it Global / LocalLock to lock the memory, release memory as long as the direct call to Global / LocalFree it. However, in this lesson we use only traditional methods, because there are many other parts of the source code is written in this way.

Documents WIN32 I / O API and from under DOS is almost identical appearance (Translator's Note: Perhaps no matter how different internal realization, it is conceivable that all of the file system exposed to the application writers should be the interface is basically the same function), The only difference under the DOS interrupt handling file I / O function into a call to the API. The following are the basic steps:

  1. CreateFile function calls to generate a document, this function can be applied in many ways, in addition to disk files, we can also be used to open the communication port, pipe, or the console driver. If successful, will return to point to a file or device handle. You can then use the handle to complete the document or the operation of equipment.
    SetFilePointer call to move the pointer over the document to read and write would like to place. .
  2. Then calls the ReadFile or WriteFile to complete the actual reading and writing. These functions will be to handle the documents and data between memory, so keep your own allocation of memory to do chores such as complicated.
  3. Call CloseHandle to close the file. The function to accept a previously opened file handle.

Content:

The following code segment demonstrated: to open a "Open File" dialog box, users can choose to open a text file, and then in an edit control to open the contents of the text file, another user can edit the content of 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, ADDR 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, hwndEdit
;==============================================
; Initialize the 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
. ELSEIF uMsg == WM_SIZE
mov eax, lParam
mov edx, eax
shr edx, 16
and eax, 0ffffh
invoke MoveWindow, hwndEdit, 0,0, eax, edx, TRUE
. ELSEIF 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 CloseHandle, 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, hwndEdit
. else
invoke DestroyWindow, hWnd
. endif
. endif
. ELSE
invoke DefWindowProc, hWnd, uMsg, wParam, lParam
ret
. ENDIF
xor eax, eax
ret
WndProc endp
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

WM_CREATE message processing, we create an edit control. Please note that we control the size of the relevant parameters are set to 0, because we will be re-set the size of the edit control, making its coverage of the entire parent window client area.
Note: in this case we do not need to call ShowWindow to display the edit control, because in the time of the creation has been in its style WS_VISIBLE flag is set, in the creation of the parent window can also use this little technique.

;==============================================
; Initialize the 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

Created edit control, we ofn variables, then the initial members. Because later when you save the file structure but also the use of the variables, so here is only used to initialize part of the public. WM_CREATE message processing part of such an excellent place to initialize.

. ELSEIF uMsg == WM_SIZE
mov eax, lParam
mov edx, eax
shr edx, 16
and eax, 0ffffh
invoke MoveWindow, hwndEdit, 0,0, eax, edx, TRUE

When the main window to change the size of some customers, our application will receive the message WM_SIZE. Of course the first time the window is displayed, we will receive the message. To receive this message, the main window must have CS_VREDRAW and CS_HREDRAW style. We should move the zoom control on the editorial here. We want to edit control window into our customers the same area, so come to be the parent window client area size. Included in these values in the lParam parameter, lParam is a part of the high character of the high customer area, at the end of the word is part of the wide-area customers. Then we call function MoveWindow to re-adjust the size of edit control, the function can not only move the location of the window, and can change the size of the window.

. 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

When the user selects the File / Open menu item, we fill the other members of ofn, and then call the function GetOpenFileName show a "Open File" dialog box.

. 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 the CreateFile function to open. We set the flag to allow the document to read and write functions. Paper we return to open the file handle stored in a global variable for later use. CreateFile function is widely used, the prototype is as follows:

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

dwDesiredAccess want to carry out the operation specified.

  • 0 to open the file query its properties.
  • Time to open the file GENERIC_READ
  • Open the file to write GENERIC_WRITE.
dwShareMode file sharing mode specified.
  • 0 to prevent other processes to share, that is, when you open the file, other processes want to open the file will fail.
  • FILE_SHARE_READ time to allow other processes.
  • Allow other processes to write FILE_SHARE_WRITE.

The attributes in lpSecurityAttributes invalid under WIN95.
For dwCreationDistribution designated documents generated in their presence have been in existence and not the action should be done.

  • CREATE_NEW generate a new document. If the file already exists will fail.
  • CREATE_ALWAYS regardless of whether there are documents to generate a new document.
  • OPEN_EXISTING open documents exist. If the file does not exist will fail.
  • OPEN_ALWAYS open the file, if the file does not exist is generated, which is set in dwCreationDistribution as CREATE_NEW flag.
  • TRUNCATE_EXISTING open the file. Opened to reduce the length of the file to zero (that is completely not the original file). This requires the calling process must have the right to GENERIC_WRITE, if the specified file does not exist, the function returns failure.

dwFlagsAndAttributes attributes specified file.

  • The document FILE_ATTRIBUTE_ARCHIVE general attributes of the documents in the archives. Users can use the flag to mark the delete and backup files.
  • FILE_ATTRIBUTE_COMPRESSED file or directory is compressed. The document which is compression of all data generated for the new directory is the subdirectory and file should be compressed.
  • The document FILE_ATTRIBUTE_NORMAL attribute set does not have a general. The flag can only be used alone.
  • The document is FILE_ATTRIBUTE_HIDDEN hidden files when browsing the file directory when the general would not show it.
  • FILE_ATTRIBUTE_READONLY the file is read-only document. Applications which can be read, but can not write.
  • The document is FILE_ATTRIBUTE_SYSTEM system files.
invoke GlobalAlloc, GMEM_MOVEABLE or GMEM_ZEROINIT, MEMSIZE
mov hMemory, eax
invoke GlobalLock, hMemory
mov pMemory, eax

File open, we will be a memory allocation API functions for subsequent use ReadFile and WriteFile. We use signs to make GMEM_MOVEABLE memory blocks WINDOWS always move to a reliable memory, GMEM_ZEROINIT told WINDOWS allocation of memory to buy just to zero. GlobalAlloc call if successful, will be returned in eax handle memory block, we pass the handle to get GlobalLock function pointer point to the memory block.

invoke ReadFile, hFile, pMemory, MEMSIZE-1, ADDR SizeReadWrite, NULL
invoke SendMessage, hwndEdit, WM_SETTEXT, NULL, pMemory

Memory blocks can be used to make, we call the ReadFile function to read data from the document. For the first time to open documents on the offset of the pointer 0, like in this case we move forward from the time offset 0. ReadFile first parameter is the file handle, the second parameter is a pointer to memory block, the next parameter is the length of time data, the fourth parameter is a pointer to the parameters of type DWORD pointer, it used to store the actual length of time data. After reading the post, we store the contents of the edit control, which used to complete messaging, we have news WM_SETTEXT to the edit control, which contains the lParam parameter points to memory block pointer. To here, edit control can display its customers of the contents of the file.

invoke CloseHandle, hFile
invoke GlobalUnlock, pMemory
invoke GlobalFree, hMemory
. endif

We no longer need to make the document open, because our aim is to save the modified data to another file rather than the previous one to document. Therefore, we can call CloseHandle to close the file. Next, we unlock the memory block, and then release it. In fact we can not release memory block, and in the subsequent re-use operation. In order to demonstrate the reasons we chose to release it.

invoke SetFocus, hwndEdit

When the Open File dialog box displayed on the screen when the input focus to the dialog. Therefore, after the closure of the dialog box, we must focus on the switch to the edit control. Now open the file by the end of the stage, the user can edit them to open the file. When the user wants to modify the content after saved to the disk, it is important to choose File / Save menu item, then save the file will display a dialog box. In fact, show the dialog box and save the file to open the file dialog to open the same basic. You can even feel that their only function in different but not the same as the name. Here can reuse most of the previous set ofn a member variable value.

mov ofn.Flags, OFN_LONGNAMES or \
OFN_EXPLORER or OFN_HIDEREADONLY

This case we will generate a new document, they must not have OFN_FILEMUSTEXIST and OFN_PATHMUSTEXIST flag. dwCreationDistribution parameters should be CREATE_NEW flag. Code and open the next dialog box asking essentially the same. Final call:

invoke SendMessage, hwndEdit, WM_GETTEXT, MEMSIZE-1, pMemory
invoke WriteFile, hFile, pMemory, eax, ADDR SizeReadWrite, NULL

Now we have the revised control data from the editor to write back to memory blocks, and then written back to memory block from a new document.



Assembly Language Tutorial Articles


Can't Find What You're Looking For?


Rating: Not yet rated

Comments

No comments posted.