write struct as raw data to file
Ali Çehreli
acehreli at yahoo.com
Sun Sep 26 16:03:22 UTC 2021
Correcting my sloppy code. :)
On 9/26/21 8:53 AM, Ali Çehreli wrote:
> // We need an array Ses (length of 1 in this case)
> auto ses = new S[1];
Allocating a dynamic array there is egregious pessimization. The
following works the same but this time the static array of a single S
will be on the stack:
S[1] ses;
> // Note the array of S passed to rawWrite
> File(name, "w").rawWrite([S(42, 1.5)]);
Similarly, a temporary dynamic array is created there. Instead, we can
have single S and make a slice of length 1 from that element:
// Note the array of S passed to rawWrite
auto s = S(42, 1.5);
File(name, "w").rawWrite((&s)[0..1]);
The expression passed to rawWrite is complicated. It takes advantage of
D's "make a slice from a pointer" feature.
- &s is a pointer to variable s
- If p is a pointer, the syntax p[0..length] makes a slice of 'length'
elements starting from 'p'.
In this case, we are treating the variable 's' as a slice of 1.
Ali
More information about the Digitalmars-d-learn
mailing list