I’m having a problem with the SetLength command.
It’s basically this problem:
I work with WindowsAPI only as good as I can. My goal is to set a certain size to a dynamic array of chars:
Here is some code to understand:
var
thefile : array of char;
// or thefile : array [0..9999] of char; // <---- not really a good way, works tho
FileHandle := CreateFileA(paramstr0, GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
dwSize := GetFileSize(FileHandle,NIL);
SetFilePointer(FileHandle, 0, nil, FILE_BEGIN);
SetLength(TheFile, dwsize); // <--- I can't use this
ReadFile(FileHandle, thefile[1], dwSize , dwRead, nil);
CloseHandle (FileHandle);
CloseHandle(CreateFileA (sfile, 0, 0,NIL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,0));
FileHandle := CreateFileA(sFile, GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0);
WriteFile (FileHandle, thefile, dwSize, testCardinal, NIL);
CloseHandle (FileHandle);
How can I replace SetLength? I would like also to understand how Windows/Delphi allocates the array in memory etc. Thank you for your help
You have several flaws in your code
When you uses the CreateFile function you must check the returned handle against the INVALID_HANDLE_VALUE.
Always you must use try .. finally to free the resources.
You are trying to use the ReadFile function reading the contents inside of the
thefilebuffer using a index 1, this is wrong you must use a index 0 because the dynamic arrays are zero index based.you are using this code
To create an empty file and then using again the CreateFile function to open and write the file, you can do the same in one step
Try this improved version of your code.
Btw, there is nothing wrong with use SetLengh, the problem is explained in the point 3.