开发者

Generic editable functions in C using void*

开发者 https://www.devze.com 2023-01-16 06:03 出处:网络
I fall in some problem. I need to write some function like memcpy(void*, const void*), which its signature should be:

I fall in some problem.

I need to write some function like memcpy(void*, const void*), which its signature should be:

void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len)

I noticed that, in many implementation of memcpy, we cast void* to char*, but I think this is not the case of me, as the arrayCopy function needed to be used on arrays of many开发者_Python百科 types including structs.

So, how can I accomplish this?

EDIT: the source code might be something like that:

#include <stdio.h>
#include <string.h>

void arrayCopy(void *, int, const void *, int, int, size_t);

int main(void)
{
    int i;
    int dest[10] = {1};
    int src [] = {2, 3, 4, 5, 6};

    arrayCopy(dest, 1, src, 0, 5, sizeof(int));

    for (i=0; i<10; i++) printf("%i\n", dest[i]);

    return 0;
}

void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len, size_t size)
{
    char *cdest = (char*) dest;
    const char *csrc = (char*) src;
    int i;

    len *= size;

    if (dest == src)
    {
        printf("Same array\n");
    }else
    {
        cdest += (dIndex * size);
        csrc += (sIndex * size);
        for (i=0; i<len; i++)
            *cdest++ = *csrc++;
    }
}

Thanks.


"char * " is just a bunch bytes, everything in C is ultimately bytes - you can cast a pointer to any data structure to char* (you will also need to know the size in memory of the structure)


The function must have an element-size info, eg:

void *arrayCopy(void *dest, size_t di,const void *src, size_t si, size_t num, size_t esize)
{
  char *cdest = (char*) dest;
  const char *csrc = (char*) src;
  return memcpy( &cdest[esize*di], &csrc[esize*si], esize*num );
}
...
arrayCopy(dest, 1, src, 0, 5, sizeof*src);


You cannot work with objects of type void. The Standard doesn't allow that. So you need to cast the void away, and the best type to use is unsigned char. There's a guarantee by the Standard that unsigned char can access all bits of any other type representable in your system.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号