Variable handling behavior + DllCall + strings

Discuss the future of the AutoHotkey language
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
GitHub: cocobelgica

Variable handling behavior + DllCall + strings

14 May 2014, 03:43

So I was testing some stuff and found a slight behavioral difference on how v.1.1 and v2
handle variable(s) passed to DllCall() when the function expects the variable to contain or
point to a string - whether to be modified or not. See examples below:

Example 1: Pass variable as is, use Str as type, both AHK builds behave the same

Code: Select all

nSize := VarSetCapacity(lpFilename, 512, 0)
DllCall("GetModuleFileName", "Ptr", 0, "Str", lpFilename, "UInt", nSize)
MsgBox %lpFilename%
Example 2: Pass the address of the variable and use StrGet, use Ptr as type, both AHK builds behave the same

Code: Select all

nSize := VarSetCapacity(lpFilename, 512, 0)
DllCall("GetModuleFileName", "Ptr", 0, "Ptr", &lpFilename, "UInt", nSize)
MsgBox % StrGet(&lpFilename)
Example 3: Pass address, use Ptr as type, don't use StrGet, v.1.1 displays blank; v2 displays the string

Code: Select all

nSize := VarSetCapacity(lpFilename, 512, 0)
DllCall("GetModuleFileName", "Ptr", 0, "Ptr", &lpFilename, "UInt", nSize)
MsgBox %lpFilename%
However, for Example 3, although v2 displays the string, passing the variable to StrLen returns 0. Type() returns String.

Code: Select all

nSize := VarSetCapacity(lpFilename, 512, 0)
DllCall("GetModuleFileName", "Ptr", 0, "Ptr", &lpFilename, "UInt", nSize)
MsgBox %lpFilename% ; Shows string
MsgBox % StrLen(lpFilename) ; returns 0
MsgBox % StrLen(StrGet(&lpFilename)) ; this one works
just me
Posts: 6552
Joined: 02 Oct 2013, 08:51
Location: Germany

Re: Variable handling behavior + DllCall + strings

14 May 2014, 11:24

Running Example 3, AHK 1.1.15.00 (U64) MsgBox is showing the file name as well as v2 for me, if I add #NoEnv to the script, which is default for v2. To access the variable with other commands you need a prior VarSetCapacity(lpFileName, -1).
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
GitHub: cocobelgica

Re: Variable handling behavior + DllCall + strings

14 May 2014, 11:29

That explains it :-). Thanks just me. I guess I didn't read this part in the docs:
In v1.0.44.03+, specify -1 for RequestedCapacity to update the variable's internally-stored string length to the length of its current contents. This is useful in cases where the variable has been altered indirectly, such as by passing its address via DllCall(). In this mode, VarSetCapacity() returns the length in bytes rather than the capacity.

Return to “AutoHotkey v2 Development”

Who is online

Users browsing this forum: No registered users and 4 guests