memcpy in D

Marco Leise Marco.Leise at gmx.de
Sun Jun 30 22:10:59 PDT 2013


Am Sun, 30 Jun 2013 07:07:23 -0400
schrieb "Tyro[17]" <ridimz at yahoo.com>:

> What is the equivalent of memcpy
> 
> module memcopy;
> 
> immutable ADDRESS_BUS_SIZE = 20; // 2^20 address bus
> byte memory[1 << ADDRESS_BUS_SIZE];
> 
> void main()
> {
> 	ushort val = 12345;
> 
> 	for (int i = 0x12340; i < 0x1234A; i+= 2) {
> 		memcpy (&memory[i], &val, sizeof val); // D way???
> 		val++;
> 	}
> 
> 	for (int i = 0x12340; i < 0x1234A; i+= 2) {
> 		memcpy (&val, &memory[i], sizeof val); // D way???
> 		writefln("%x", val);
> 	}
> }
> 
> achieved in D? I am trying not to use memcpy or any function from the C API.
> 
> Thanks,

While they are in the C stdlib, there is nothing really C
specific about them. Just use them. In your case GCC would
recognize a memcpy call with known length (2 bytes) and inline
the call. From there I guess the optimizer can figure
something out that runs fast.

That said how about this in D:

ushort val = 12345;

for (int i = 0x12340; i < 0x1234A; i+= 2)
	*cast(ushort*) &memory[i] = val++;

for (int i = 0x12340; i < 0x1234A; i+= 2) {
	val = *cast(ushort*) &memory[i]
	writefln("%04x", val);
}


-- 
Marco



More information about the Digitalmars-d-learn mailing list