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

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

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

Post by iseahound » 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: 4709
Joined: 17 Jul 2016, 01:02
Contact:

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

Post by Helgef » 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: 9560
Joined: 30 Sep 2013, 04:07
Contact:

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

Post by lexikos » 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).

Post Reply

Return to “Tips and Tricks (v1)”