String appending - how does it work

Get help with using AutoHotkey and its commands and hotkeys
expert_vision
Posts: 21
Joined: 13 Jan 2014, 10:47

String appending - how does it work

24 Jan 2015, 10:55

I want to append a string to a buffer received from a DllCalll containing a null terminated string, but instead of being appended it's simply placed at the start of the string.

The code snippet below depicts the issue.

Code: Select all

;~ ANSI only
VarSetCapacity(string, 8, 0)
DllCall("RtlFillMemory", "Ptr", &string, "UInt", 3, "UChar", Asc("a")&0xff) ; fill in the first 3 bytes with ASCII value of "a"
MsgBox % string ; all good; result is "aaa"
Loop % 8
	bin1 .= *(&string+A_Index-1) . "(" . Chr(*(&string+A_Index-1)) . ")" . "_"
MsgBox % bin1 ; all good; 97 97 97 0 => a NULL terminated string
string .= "b" ; append "b" to "aaa"
MsgBox % string ; result is "b" .. why?
Loop % 8
	bin2 .= *(&string+A_Index-1) . "(" . Chr(*(&string+A_Index-1)) . ")" . "_"
MsgBox % bin2 ; 98 0 97 0 . "b" was not appended, was simply assigend to string. Why?
User avatar
LinearSpoon
Posts: 156
Joined: 29 Sep 2013, 22:55

Re: String appending - how does it work

24 Jan 2015, 11:29

Add VarSetCapacity(string,-1) after the DllCall. The DllCall modifies the string, AHK's internal string length counter now has the wrong value. Append is probably optimized to jump to the end of the string based on the length counter rather than searching for the NULL. VarSetCapacity(string,-1) asks AHK to update the length of the string explicitly.
expert_vision
Posts: 21
Joined: 13 Jan 2014, 10:47

Re: String appending - how does it work

24 Jan 2015, 11:55

I missed that in docs. Thanks!
lexikos
Posts: 6742
Joined: 30 Sep 2013, 04:07
GitHub: Lexikos

Re: String appending - how does it work

24 Jan 2015, 17:16

If you use "str", string instead of "ptr", &string, DllCall will do it for you automatically.

Return to “Ask For Help”

Who is online

Users browsing this forum: Albireo, Bing [Bot], Google [Bot], jamesldnaylor, roikl289, Sam_, supersonic23, yuyu and 163 guests