memcpy in D
Steven Schveighoffer
schveiguy at yahoo.com
Sun Jun 30 05:56:54 PDT 2013
On Sun, 30 Jun 2013 07:40:31 -0400, monarch_dodra <monarchdodra at gmail.com>
wrote:
> 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.
D's memcpy is C's memcpy. So I don't know why it would be slower. Note
that with DMD on windows 32 bit, it uses DMC, which may vary in
performance from MSVC memcpy.
Using vector assignment may or may not use memcpy. It may be the slower
one, but I don't know. If it can be inlined, it certainly would be faster
for small values.
-Steve
More information about the Digitalmars-d-learn
mailing list