lawful_neutral
lawful_neutral

Reputation: 673

Copying bytes without memcpy

I have several variables of different types stored in a char array. Normally I would write them to the array this way:

int a = 5;
memcpy(offset, (char*)&a, sizeof(int))

However, memcpy doesn't work in OpenCL kernels. What would be the easiest way to do the same without this function?

Upvotes: 3

Views: 1860

Answers (3)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11920

You can use vload and vstore commands for just 1-16 bytes for char type and 4-64 bytes for int type and 8-128 bytes for long type. This could be advantageous or disadvantageous depending on the total cores' memory accessing patterns.

I didnt check but this should trigger a compiler to use fast sse avx load and store on a cpu and use full bus width for gpu. Also alignment conditions are met because it is undefined behaviour for unaligned accessing with load store.

You need to copy non aligned head part of array first. If there is any .

Upvotes: 2

Malcolm McLean
Malcolm McLean

Reputation: 6404

You can easily enough provide mymemcpy

  void mymemcpy(unsigned char *dest, const unsigned char *src, size_t N)
  {
     size_t i;

     for(i=0;i<N;i++)
       dest[i] = src[i];
  }

However it's not very efficient because most copies are aligned copies of multiples of 4 or 8 bytes. If you can work out that alignment is 8 bytes, copy in units of unsigned long long. Sometimes it's even worth padding a buffer to bring it up to a multiple of 8 bytes.

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477140

How about a loop?

int a;
unsigned char * p = (unsigned char *)&a;
for (int i = 0; i != sizeof(int); ++i) offset[i] = p[i];

Upvotes: 5

Related Questions