Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do something like a memcpy in D

I have a memory location a and I want to copy a certain amount of bytes to another location fast, how would I do this in D ?

For example how would i do this:

int main()
{
    void* src_data = 0x40001255;
    void* dst_data = 0x47F22000;
    u32 size = 0x200;
    memcpy(dst_data, src_data, size);
}

Also how would fill a struct fast:

struct data_struct
{
    u32 block1;
    u32 block2;
    u32 block3;
    u32 block4;
    u32 block5;
    u62 block6;
    u128 bigblock;
} data_struct_t;

int main()
{
    void* src_data = 0x40001255;
    struct data_struct_t dst_data; 
    u32 size = sizeof(data_struct);
    memcpy(dst_data, src_data, size);
}

Thanks! Roel

like image 951
Roel Van Nyen Avatar asked Sep 02 '11 09:09

Roel Van Nyen


People also ask

What can I use instead of memcpy?

memmove() is similar to memcpy() as it also copies data from a source to destination.

What is the difference between memset and memcpy?

memcpy() copies from one place to another. memset() just sets all pieces of memory to the same.

Is Memmove faster than memcpy?

"memcpy is more efficient than memmove." In your case, you most probably are not doing the exact same thing while you run the two functions. In general, USE memmove only if you have to. USE it when there is a very reasonable chance that the source and destination regions are over-lapping.

How memcpy () and Memmove () do compare in terms of performance?

That memmove might be slower than memcpy is because it is able to handle overlapping memory, but memmove still only copies the data once. profile it on the platform you're interested in the timings for. However, the chances of you writing a better memmove than memmove seems unlikely.


2 Answers

Assigning to a slice will perform an array copy, which calls memcpy internally.


void main()
{
    void* src_data = 0x40001255;
    void* dst_data = 0x47F22000;
    uint size = 0x200;
    dst_data[0..size] = src_data[0..size];
}

For the second one:


struct data_struct
{
    uint block1, block2, block3, block4, block5;
    ulong block6;
    uint[4] bigblock;
}

void main()
{
    auto src_data = cast(data_struct*) 0x40001255; // unaligned, WTF?!
    auto dst_data = *src_data;
}
like image 139
FeepingCreature Avatar answered Sep 21 '22 22:09

FeepingCreature


Note that you also have access to C's memcpy in D. D can directly access C's whole standard library.

like image 28
dsimcha Avatar answered Sep 18 '22 22:09

dsimcha