DllCall Shortcuts, VarSetCapacity laziness using Chr(), Avoiding NumPut()

Put simple Tips and Tricks that are not entire Tutorials in this forum
iseahound
Posts: 613
Joined: 13 Aug 2016, 21:04
GitHub: iseahound

DllCall Shortcuts, VarSetCapacity laziness using Chr(), Avoiding NumPut()

26 May 2020, 20:12

@Helgef

What's your opinion on code like this:

Code: Select all

VarSetCapacity(x, 16, 0), x := Chr(0x1)
and there was another way to do it as well (up to 16 bytes) but I forgot.

Maybe VarSetCapacity(x, 16, 0), x := 0xFFFFFFF?
Helgef
Posts: 4461
Joined: 17 Jul 2016, 01:02
Contact:

Re: DllCall Shortcuts, VarSetCapacity laziness using Chr(), Avoiding NumPut()

26 May 2020, 22:38

That's pretty horrible. You can write an entire struct of any size in one string assignment as long as it can be represented by one.
VarSetCapacity(x, 16, 0), x := 0xFFFFFFF
No.

Cheers.
lexikos
Posts: 7086
Joined: 30 Sep 2013, 04:07
GitHub: Lexikos

Re: DllCall Shortcuts, VarSetCapacity laziness using Chr(), Avoiding NumPut()

30 May 2020, 00:44

In general, any code that performs a direct assignment after setting the capacity of a variable (and still relies on the previous capacity or address) is suspect. In this case you can see that a single-character value is being assigned, but in general, a direct assignment may free the variable's previous memory block and invalidate any assumptions about capacity. This can happen even when assigning a non-empty string to a variable which has sufficient capacity, if the value being assigned is known to be allocated with malloc and would otherwise have to be immediately freed (it's done to avoid unnecessary copying). For example:

Code: Select all

VarSetCapacity(x, 1000, 0)
s := ""
Loop 257
    s .= "a"
MsgBox % VarSetCapacity(x)  ; 1000
x := SubStr(s, 1, -1)  ; SubStr allocates memory to return the substring.
MsgBox % VarSetCapacity(x)  ; 512 (if Unicode)
; Tested on v1.1.32.00
SubStr(s, 2) will not have this effect because in that case, SubStr can just return a pointer into the original string. After SubStr returns, the expression evaluator copies the result (unless the expression is ending and the result is being discarded).

Return to “Tips and Tricks”

Who is online

Users browsing this forum: No registered users and 5 guests