memcpy in D

monarch_dodra monarchdodra at gmail.com
Sun Jun 30 04:40:31 PDT 2013


On Sunday, 30 June 2013 at 11:07:24 UTC, Tyro[17] wrote:
> 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,

You could do it with ubyte a vector copy:

--------
void * dmemcpy ( void * destination, const void * source, size_t 
num ) pure nothrow
{
     (cast(ubyte*)destination)[0 .. 
num][]=(cast(const(ubyte)*)source)[0 .. num];
     return destination;
}
--------

Doing it this way has the advantage of being CTFE-able, and 
(potentially) faster, as everything I ever read about D's memcpy 
is that it is slow.


More information about the Digitalmars-d-learn mailing list