Sponsors

Monday, January 25, 2016

Modify a Constant String in Delphi

In the following code example, we will use the winAPI to help us modify a const value. Since you would not normally need to modify a constant value, we will just do this for the sake of demonstration.

procedure ModifyConstString;
var
me: string;
p: Pointer;
I, i2: cardinal;
CONST
MyString: ansiString ='Try to modify';
MyString2: ansiString ='Modified!!!!!';
begin
p:=(@MyString[1]);
VirtualProtect(p, length(MyString), $40 ,@I);//$40=PAGE_EXECUTE_READWRITE
CopyMemory(p,@MyString2[1],Length(MyString));
Edit1.Text:=String(MyString);
end;

The first thing I did was get the address of the first character of myString as a pointer which we declared as P. The next thing we will need to do is make the const string writable. Constant values are generally write protected in memory. If we do not make the code writable before using the copymemory function, we will incur an access violation exception. Therefore, we must call VirtualProtect to grant us write access. Finally, we will use the copymemory function to copy the new data to the constant's location. Finally, we must ensure that the value we are writing to the constant's place is of the same byte length since its memory size cannot be modified.

No comments:

Post a Comment